问题描述
我有2个查询.一个可以找到价值列大于150,000的地方,我需要条目计数.第二个是该总和而不是计数. 计数运行完美,但总和崩溃并提供此错误
{''cast to value type'system.decimal'失败,因为 物质价值为无效.结果类型的通用参数要么 或查询必须使用无效类型."}
工作代码:
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?明确施放到Sum中解决问题:
var excessSum = CloseDealNonHost = closedDealNonHost.Any() ? closedDealNonHost .Where(x => x.Value > 150000) .Sum(x => (decimal?) x.Value) : 0;
问题是由于LINQ表达式生成的SQL,在C#结束时,它将尝试返回decimal无法容纳null值,因此错误.
您可能会看到: linq到实体:查询.
问题描述
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
{"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."}
Working code:
var excessCount = closedDealNonHost.Any() ? closedDealNonHost.Where(x => x.Value > 150000).Count() : 0;
Crashing Code:
var excessSum = CloseDealNonHost = closedDealNonHost.Any() ? closedDealNonHost.Where(x => x.Value > 150000).Sum(x => x.Value) : 0;
推荐答案
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;
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.
You may see: Linq To Entities: Queryable.Sum returns Null on an empty list