处理LINQ sum表达式中的null [英] Handle null in LINQ sum expression
问题描述
我正在使用LINQ查询来查找列的总和,并且在少数情况下该值可能为null
I am using a LINQ query to find sum of a column and there is a slight chance that the value might be null in few cases
我现在使用的查询是
int score = dbContext.domainmaps.Where(p => p.SchoolId == schoolid).Sum(v => v.domainstatement.Score ?? 0);
其中domainstatement
可以为null,得分也可以为
where domainstatement
can be null and score also can be null
现在执行此查询后,我得到了错误
Now after executing this query, I am getting the error
强制转换为值类型'Int32',因为实例化值为null.结果类型的通用参数或查询必须使用可为空的类型.
The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
那么我该如何有效地处理null异常,并将sum作为INT值返回?
So how can I handle null exceptions effectively and return sum as an INT value?
推荐答案
此处
Sum(v => v.domainstatement.Score ?? 0);
您只是将null-coalescing运算符放在了错误的位置.通常,通过将非可空类型提升为可空类型(无需DefaultOrEmpty
并且需要空检查)来解决此类错误,但是在这里您已经具有可空类型,并且使用空合并运算符可以执行与错误消息相反的操作告诉您-查询必须使用可为空的类型.
you've just put the null-coalescing operator on the wrong place. Usually such error is solved by promoting the non nullable type to nullable (no DefaultOrEmpty
and null checks are needed), but here you already have a nullable type, and with null-coalescing operator you did the opposite of what the error message is telling you - the query must use a nullable type.
只需将其移到
Simply move it after the Sum
call and the issue is gone:
Sum(v => v.domainstatement.Score) ?? 0;
这篇关于处理LINQ sum表达式中的null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!