用where子句求和一个IQueryable列 [英] Sum a IQueryable Column with where clause
问题描述
我有2个查询.一个发现值列大于150,000的地方,我需要输入计数.第二个是总和而不是计数. 计数工作正常,但总和崩溃并提供此错误
I have 2 queries. One to find where Value column is greater than 150,000 and i need the count of entries. The second one is the sum of that rather than count. The Count works perfectly but the sum crashes and provides this error
{强制转换为值类型'System.Decimal'的原因是 物化值为null.结果类型的通用参数 否则查询必须使用可为空的类型.}
{"The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."}
工作代码:
var excessCount = closedDealNonHost.Any() ? closedDealNonHost.Where(x => x.Value > 150000).Count() : 0;
崩溃代码:
var excessSum = CloseDealNonHost = closedDealNonHost.Any() ? closedDealNonHost.Where(x => x.Value > 150000).Sum(x => x.Value) : 0;
推荐答案
您可以通过在Sum
中显式转换为decimal?
来解决此问题,例如:
You can solve the issue by explicitly casting to decimal?
in Sum
like:
var excessSum = CloseDealNonHost = closedDealNonHost.Any() ? closedDealNonHost
.Where(x => x.Value > 150000)
.Sum(x => (decimal?) x.Value) : 0;
此问题是由于从LINQ表达式生成了SQL,在C#端它将尝试返回不能容纳null
值的decimal
,因此会出错.
The issue is due to generated SQL from LINQ expression, and at C# end it will try to return decimal
which can't accommodate a null
value, hence the error.
您可能会看到: 查看全文