我正在尝试将解决方案升级到新的 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/