c# - 从 dotnet Core 2.2.6 更改为 3.0.0 后出现 EF Linq 错误

标签 c# .net-core entity-framework-core-3.0

我正在尝试将解决方案升级到新的 Core Framework 3.0.0。 现在我遇到一个我不明白的小问题。

你看,这个方法在2.2.6中没有问题:

public async Task<IEnumerable<ApplicationUser>> GetBirthdayUsersCurrentMonth()
    {
        return await ApplicationDbContext.Users
            .Where(x => x.Gender != ApplicationUser.GenderTypes.generic)
            .Where(x => x.BirthDate.GetValueOrDefault().Month == DateTime.Now.Month)
            .Where(x => x.RetireDate == null)
            .OrderBy(x => x.BirthDate.GetValueOrDefault())
            .ToListAsync();
    }

现在在 3.0.0 中,我收到一个 Linq 错误,内容如下:

InvalidOperationException: The LINQ expression 'Where( source: Where( source: DbSet, predicate: (a) => (int)a.Gender != 0), predicate: (a) => a.BirthDate.GetValueOrDefault().Month == DateTime.Now.Month)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

当我禁用此行时:

.Where(x => x.BirthDate.GetValueOrDefault().Month == DateTime.Now.Month)

错误消失了,但当然我得到了所有用户。我在这个查询中看不到错误。 这可能是 EF Core 3.0.0 中的一个错误吗?

最佳答案

原因是 EF Core 3 中已禁用隐式客户端评估。

这意味着以前,您的代码没有在服务器上执行 WHERE 子句。相反,EF 将所有行加载到内存中并计算内存中的表达式。

要在升级后解决此问题,首先需要弄清楚 EF 到底无法转换为 SQL 的是什么。我的猜测是调用 GetValueOrDefault(),因此尝试像这样重写它:

.Where(x => x.BirthDate != null && x.BirthDate.Value.Month == DateTime.Now.Month)

关于c# - 从 dotnet Core 2.2.6 更改为 3.0.0 后出现 EF Linq 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58074844/

相关文章:

wpf - 是否可以在 Windows 7 Embedded 上运行 .NET core 3.1 应用程序?

azure - Azure Function App VS 2019 .NET 3.0 中出现错误 - 找不到方法 : 'IFunctionsHostBuilder.get_Services()'

c# - 具有精确表达式的起订量<Func<TEntity, bool>>

c# if not null then assign value 的简写

c# - .NET Core - 在模型中获取 DbContext

.net-core - 在使用Http.sys和URLPrefix时,如何配置dotnet core 3来提供React SPA?

c# - 如何在单元测试中验证 EF Core DBContext 配置

c# - 我的上下文不是从 Entity Framework Core 中的 DbContext 继承的

c# - 使用 VisualStyles 的控件边框颜色

c# - 如何转到 Novacode Docx 中的下一页