c# - Sum() 在 Entity Framework 查询中返回 null

标签 c# linq entity-framework

我有一个包含这些行的大型 Entity Framework 查询。

var programs = from p in Repository.Query<Program>()
               where p.OfficeId == CurrentOffice.Id
               let totalCharges = p.ProgramBillings.Where(b => b.Amount > 0 && b.DeletedDate == null).Select(b => b.Amount).Sum()
               let totalCredits = p.ProgramBillings.Where(b => b.Amount < 0 && b.DeletedDate == null).Select(b => -b.Amount).Sum()
               let billingBalance = (totalCharges - totalCredits)

当我具体化数据时,出现以下错误:

The cast to value type 'Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

如果我按如下方式更改我的查询(添加到两个类型转换中),错误就会消失。

var programs = from p in Repository.Query<Program>()
               where p.OfficeId == CurrentOffice.Id
               let totalCharges = (decimal?)p.ProgramBillings.Where(b => b.Amount > 0 && b.DeletedDate == null).Select(b => b.Amount).Sum()
               let totalCredits = (decimal?)p.ProgramBillings.Where(b => b.Amount < 0 && b.DeletedDate == null).Select(b => -b.Amount).Sum()
               let billingBalance = (totalCharges - totalCredits)

我不明白这个。 ProgramBilling.Amount是不可为 null 的 Decimal。如果我将鼠标悬停在 Sum() 上调用,Intellisense 说它返回类型 Decimal。然而,额外的测试证实,在我的第二个版本中,totalChargestotalCredits对于 ProgramBillings 的那些行都设置为 null没有数据。

问题:

  1. 我明白了 Sum()为空集合返回 0。在什么情况下这不是真的?

  2. 如果有时情况并非如此,那为什么当我将鼠标悬停在 Sum() 上时呢? , Intellisense 显示它返回类型 Decimal 而不是 Decimal?看来 Intellisense 和我有同样的理解。

编辑:

似乎一个简单的解决方法就是执行类似 Sum() ?? 0m 的操作.但这是非法的,给我错误:

Operator '??' cannot be applied to operands of type 'decimal' and 'decimal'

最佳答案

I understood Sum() returned 0 for an empty collection. Under what circumstances is this not true?

当您不使用 LINQ to objects 时,就像这里的情况一样。这里有一个查询提供程序将此查询转换为 SQL。 SQL 操作的 SUM 运算符具有不同的语义。

And if sometimes that is not true, then why when I hover over Sum(), Intellisense shows it returns type Decimal and not Decimal? It appears Intellisense had the same understanding that I had.

C# LINQ SUM 运算符不返回可为 null 的值;它需要有一个非空值,但 SQL SUM 运算符具有不同的语义,它在对空集求和时返回 null,而不是 0null 值是在 C# 需要非空值的上下文中提供的,这是一切都崩溃的全部原因。如果此处的 C# LINQ SUM 运算符返回可为 null 的值,则可以毫无问题地返回 null

导致此错误的是 C# 运算符和它用来表示的 SQL 运算符之间的差异。

关于c# - Sum() 在 Entity Framework 查询中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27866922/

相关文章:

c# - 使用 IEventAggregator 的 Caliburn Micro Stack 溢出异常

c# - 为什么 WP8 应用程序中的 JsonConvert.DeserializeObject 可以工作,而 WP8 ScheduledTask 却不能

c# - 如何优化此 Linq 查询以查找过去 24 小时内浏览次数最多的博客文章

c# 使用字符串参数定义在对象列表中过滤的属性

c# - ASP.NET MVC6 "The binary operator Equal is not defined"

c# - JSON 到 XML 类转换

c# - 从命令行运行时 StartupObject 的行为与修改 CSPROJ 文件时的行为不同

c# - linq to SQL Server 中的排序依据 (asc|desc) 以不同方式处理 DateTime

.net - 无法访问已处置的对象。导致此错误的一个常见原因是处置上下文

c# - IEquatable 不调用 Equals 方法