开发者

Linq: Sum of int

开发者 https://www.devze.com 2022-12-08 12:42 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消