从 dotnet Core 2.2.6 更改为 3.0.0 后的 EF Linq 错误

编程入门 行业动态 更新时间:2024-10-21 11:55:26
本文介绍了从 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() 的调用显式切换到客户端评估

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 中的错误吗?

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 错误

本文发布于:2023-11-14 04:29:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586221.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   Core   dotnet   Linq   EF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!