Linq: Sum of int
I am getting "The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type" When executing Sum() of my empty statement. ResultView works fine, but either
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);
either
var r = from v in DataContext.Visits
join bs in DataContext.BaseContents on v.BaseContentID equals bs.Id
where (bs.CreatedBy == userId) && (v.DateVisi开发者_如何学运维ted.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);
fails with same exception.
Try this (updated):
int number = r.Sum(v => (int?)v.Counter) ?? 0;
Could you include some sample data? At the very least you might grab r.ToList() and look at the values by hand. From what I can see this looks like it should work fine. Also make sure that v.BaseContentID, bs.Id and v.DateVisited are not nullable. (especially the ID columns) Any nullable integers that are referenced could cause that exception. Not just the ones in the Select clause
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);
Seems like putting && (v.Counter != null)
would filter out all nulls for that value before running the sum.
精彩评论