将一条可音机的列与Where子句总结[英] Sum a IQueryable Column with where clause

本文是小编为大家收集整理的关于将一条可音机的列与Where子句总结的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有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到实体:查询.

本文地址:https://www.itbaoku.cn/post/1557106.html

问题描述

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