问题描述
我尝试执行以下代码:
await _dbContext.Customers.Select(x => x.CustomerNr).DefaultIfEmpty(0).MaxAsync() + 1;
本质上它必须从数据库中获取最高的客户编号并将其加 1.如果客户表是空的,它应该返回 0,我加 1.为什么它给我以下异常:
Essentially it has to get the highest customer number from the database and add 1 to it. If the customer table is empty, it should return 0 to which I add 1. Why is it giving me the following exception:
我正在使用 .NET Core 3.1 和 EF Core 3.0.1(EF Core 3.1.0 出现相同错误)
I am using .NET Core 3.1 and EF Core 3.0.1 (Same error for EF Core 3.1.0)
推荐答案
避免使用默认值的 DefaultIfEmpty
重载 - EF Core 查询转换器不支持它.
Avoid DefaultIfEmpty
overload with default value - it's not supported by EF Core query translator.
通常也避免 DefaultIfEmpty
无参数重载用于除左外连接模式之外的任何其他内容,因为虽然支持它,但 SQL 转换非常奇怪.
Also in general avoid DefaultIfEmpty
parameterless overload for anything else than left outer join pattern because while it is supported, SQL translation is quite weird.
要解决在空集上应用 Max
、Min
和 Average
方法的问题,请使用返回 null 的可空重载
为空集,如果需要,将 null
结果转换为 0(或其他所需的魔法值).
To solve the problem with applying Max
, Min
and Average
methods on empty sets, use the nullable overloads which return null
for empty set, and convert null
result to 0 (or other desired magic value) if needed.
将其应用于您的场景将是这样的(假设 CustomerNr
类型是 int
):
Applying it to your scenario would be somethong like this (assuming the CustomerNr
type is int
):
(await _dbContext.Customers.MaxAsync(x => (int?)x.CustomerNr)) ?? 0 + 1;
这篇关于DefaultIfEmpty 异常“错误或限制"使用 EF 核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!