本文介绍了从 dotnet Core 2.2.6 更改为 3.0.0 后的 EF Linq 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to upgrade a solution to the new Core Framework 3.0.0.Now I'm having a small issue I don't understand.

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

Look, this method was unproblematic in 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 错误:

Now in 3.0.0 I get a Linq Error saying this:

InvalidOperationException: The LINQ expression 'Where( source: Where( source: DbSet, predicate: (a) => (int)a.Gender != 0), predicate: (a) => a.BirthDate.GetValueOrDefault().Month == DateTime.Now.Month)' 无法翻译.以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估

当我禁用此行时:

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

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

The error is gone but off course I get all users. And I can't see an error in this query.Could this perhaps be a bug in EF Core 3.0.0?

推荐答案

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

The reason is that implicit client evaluation has been disabled in EF Core 3.

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

What that means is that previously, your code didn't execute the WHERE clause on the server. Instead, EF loaded all rows into memory and evaluated the expression in memory.

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

To fix this issue after the upgrade, first, you need to figure out what exactly EF can't translate to SQL. My guess would be the call to GetValueOrDefault(), therefore try rewriting it like this:

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

这篇关于从 dotnet Core 2.2.6 更改为 3.0.0 后的 EF Linq 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 03:08