2

在执行空语句的 Sum() 时,我收到“无法将空值分配给 System.Int32 类型的成员,这是一个不可为空的值类型”。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);

失败,同样的例外。

4

3 回答 3

4

试试这个(更新):

int number = r.Sum(v => (int?)v.Counter) ?? 0;
于 2009-10-12T14:37:36.480 回答
1

你能包括一些样本数据吗?至少您可能会抓住 r.ToList() 并手动查看值。据我所知,这看起来应该可以正常工作。还要确保 v.BaseContentID、bs.Id 和 v.DateVisited 不可为空。(尤其是 ID 列)引用的任何可为空的整数都可能导致该异常。不仅仅是Select子句中的那些

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);
于 2009-10-12T15:15:04.920 回答
0

似乎 put&& (v.Counter != null)会在运行总和之前过滤掉该值的所有空值。

于 2009-10-12T14:38:42.170 回答