LINQ to SQL DataContext 中的空引用异常
我有一个由这段代码引起的空引用异常:
var recentOrderers = (from p in db.CMS
where p.ODR_DATE > DateTime.Today - new TimeSpan(60, 0, 0, 0)
select p.SOLDNUM).Distinct();
result = (from p in db.CMS
where p.ORDER_ST2 == "SH" &&
p.ODR_DATE > DateTime.Today - new TimeSpan(365, 0, 0, 0) &&
p.ODR_DATE < DateTime.Today - new TimeSpan(60, 0, 0, 0) &&
!(recentOrderers.Contains(p.SOLDNUM))/**/
select p.SOLDNUM).Distinct().Count();
结果是双精度类型。当我注释掉时:
!(recentOrderers.Contains(p.SOLDNUM))
代码运行良好。我已经验证了recentOrderers不为空,并且当我运行:
if(recentOrderes.Contains(0)) return;
执行时遵循此路径并返回。不知道发生了什么,因为我在上面使用了类似的代码:
var m = (from p in db.CMS where p.ORDER_ST2 == "SH" select p.SOLDNUM).Distinct();
double result = (from p in db.CUST
join r in db.DEMGRAPH on p.CUSTNUM equals r.CUSTNUM
where p.CTYPE3 == "cmh" && !(m.Contains(p.CUSTNUM)) &&
r.ColNEWMEMBERDAT.Value.Year > 1900
select p.CUSTNUM).Distinct().Count();
它也运行完美。注意到相似之处后,有人可以帮忙吗?提前致谢。
I have a Null Reference Exception Caused by this code:
var recentOrderers = (from p in db.CMS
where p.ODR_DATE > DateTime.Today - new TimeSpan(60, 0, 0, 0)
select p.SOLDNUM).Distinct();
result = (from p in db.CMS
where p.ORDER_ST2 == "SH" &&
p.ODR_DATE > DateTime.Today - new TimeSpan(365, 0, 0, 0) &&
p.ODR_DATE < DateTime.Today - new TimeSpan(60, 0, 0, 0) &&
!(recentOrderers.Contains(p.SOLDNUM))/**/
select p.SOLDNUM).Distinct().Count();
result is of double type. When I comment out:
!(recentOrderers.Contains(p.SOLDNUM))
The code runs fine. I have verified that recentOrderers is not null, and when I run:
if(recentOrderes.Contains(0)) return;
Execution follows this path and returns. Not sure what is going on, since I use similar code above it:
var m = (from p in db.CMS where p.ORDER_ST2 == "SH" select p.SOLDNUM).Distinct();
double result = (from p in db.CUST
join r in db.DEMGRAPH on p.CUSTNUM equals r.CUSTNUM
where p.CTYPE3 == "cmh" && !(m.Contains(p.CUSTNUM)) &&
r.ColNEWMEMBERDAT.Value.Year > 1900
select p.CUSTNUM).Distinct().Count();
which also runs flawlessly. After noting the similarity, can anyone help? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对 Linq 不太熟悉,但是如果没有匹配结果,.Distinct() 是否会返回 null?
I'm not super familiar with Linq, but could it be that .Distinct() returns null if there are no matching results?
尝试通过转换为列表对象(实际上:使用 .ToList() 执行它)来显式从第一个查询获取数据,然后进行比较。
Try to explicite get data from the first query by converting to a list object (actually: executing it using .ToList()) then use in comparison.