我得到“无法将null值分配给类型为System.Int32的成员,这是一个非可空的值类型”执行我的空语句的Sum()时。 ResultView工作正常,但
var r = from v in DataContext.Visits
join bs in DataContext.BaseContents on v.BaseContentID equals bs.Id
where (bs.CreatedBy == userId) && (v.DateVisited.Year == workDate.Year) &&
(v.DateVisited.Month == workDate.Month) && (v.DateVisited.Day == workDate.Day) &&
(v.IsPreviewed == false) && (bs.ProfileProjectId != null)
select v;
int? number = r.Sum( v => v.Counter);
或者
var r = from v in DataContext.Visits
join bs in DataContext.BaseContents on v.BaseContentID equals bs.Id
where (bs.CreatedBy == userId) && (v.DateVisited.Year == workDate.Year) &&
(v.DateVisited.Month == workDate.Month) && (v.DateVisited.Day == workDate.Day) &&
(v.IsPreviewed == false) && (bs.ProfileProjectId != null)
select v.Counter;
int? number = r.Sum(v);
失败并出现同样的异常。
答案 0 :(得分:4)
试试这个(更新):
int number = r.Sum(v => (int?)v.Counter) ?? 0;
答案 1 :(得分:1)
你能包含一些样本数据吗?至少你可以抓住r.ToList()并手动查看这些值。从我可以看到这看起来它应该工作正常。还要确保v.BaseContentID,bs.Id和v.DateVisited不可为空。 (尤其是ID列)引用的任何可空整数都可能导致该异常。不仅仅是选择子句
中的那些var r = from v in DataContext.Visits
join bs in DataContext.BaseContents on v.BaseContentID equals bs.Id
where (bs.CreatedBy == userId)
&& (v.DateVisited.Date == workDate.Date)
&& (!v.IsPreviewed)
&& (bs.ProfileProjectId.HasValue)
select v;
int? number = r.Sum(v => v.Counter);
答案 2 :(得分:0)
似乎put && (v.Counter != null)
会在运行总和之前过滤掉该值的所有空值。