Linq: Sum int

I get " A null value cannot be assigned to a member of type System.Int32, which is a non-nullable value type " when I execute Sum () of my empty statement. ResultView works fine, but

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);

      

or

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);

      

doesn't work with the same exception.

+2


source to share


3 answers


Try this (updated):



int number = r.Sum(v => (int?)v.Counter) ?? 0;

      

+4


source


Could you include some sample data? At least you can grab r.ToList () and look at the values ​​manually. From what I can see it looks like it should work fine. Also make sure v.BaseContentID, bs.Id and v.DateVisited are not NULL. (especially id columns). Any referenced null integers can throw this exception. Not only those listed 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);

      

+1


source


It seems like put && (v.Counter != null)

will filter out all nulls for that value before running the sum.

0


source







All Articles