0

我有以下 LINQ 语句:

var inspectorAllocSummary = context
    .UserDetails
    .Where(ud => ud.PerformAudit == true && ud.Valid == true)
    .OrderBy(ud => ud.Firstname)
    .Select(ud
        => new InspectorWorkStatusModel
           {
               InspectorName = ud.Firstname,

               ToBeCompleted = context
                   .InspectorWorkAllocations
                   .Where(x => x.UploadCOESDetails.AuditMonth
                                   == criteria.AuditMonth 
                               && x.InspectorId == ud.Id)
                   .Sum(x=> x.ToBeAudited) ?? 0,

               Completed = context
                   .COESDetails
                   .Where(x => x.UploadCOESDetails.AuditMonth
                                   == criteria.AuditMonth 
                               && x.InspectorId == ud.Id
                               && x.AuditType != null)
                   .Count()
           });

ToBeCompleted一个整数,它从数据库中获取数据,但如果它是 null 我想确保它设置为0. 我尝试了以下方法:

ToBeCompleted = context
    .InspectorWorkAllocations
    .Where(x => x.UploadCOESDetails.AuditMonth == criteria.AuditMonth
                && x.InspectorId == ud.Id)
    .Sum(x=> x.ToBeAudited) ?? 0

但我收到以下错误:

操作员 '??' 不能应用于“int”和“int”类型的操作数

我如何确保如果返回数据是null,它将被设置为零?

4

2 回答 2

1

首先,您需要将类型更改ToBeAuditedint?。问题在于它int是一个值类型,它不能包含null. 这就是为什么在您的第一种方法中您会收到错误:

转换为值类型“Int32”失败,因为具体化值为空。

有一个Sum接受可为空值的重载。因此,在ToBeAudited更改为可为空之后,这就足够了:

ToBeCompleted = context
    .InspectorWorkAllocations
    .Where(x => x.UploadCOESDetails.AuditMonth == criteria.AuditMonth
                && x.InspectorId == ud.Id)
    .Sum(x => x.ToBeAudited).Value;

您不需要??运算符,因为null值会被自动忽略(并且对于空序列Sum将返回0)。

于 2013-11-02T15:31:09.817 回答
1

if ToBeAuditedis an intthenSum永远无法返回null,它总是返回 an int。如果集合为空,它将返回 0。只需起飞?? 0

但是,如果生成的 SQL 不返回任何记录,Linq-to-SQL 和 Linq-to-Entities可能会引发错误。对于 Linq-to-SQL,一个“修复”是将基础字段转换为可为空的类型:

.Sum(x=> (int?)x.ToBeAudited) ?? 0

对于 Linq-to-Entities 的修复方法是调用.DefaultIfEmpty()

.Select(x=> x.ToBeAudited)
.DefaultIfEmpty(0)
.Sum()
于 2013-11-02T15:19:23.390 回答