简体   繁体   English

LINQ 表达式无法翻译

[英]LINQ expression could not be translated

I have the following database query where I am trying to check if there exists an item with a particular barcode that is linked to a particular mailbag.我有以下数据库查询,我试图检查是否存在具有链接到特定邮袋的特定条形码的项目。 The query is as follows:查询如下:

var exists = await dbcontext.Items
                .Include(t => t.MailBagItems)
                .ThenInclude(mt => mt.MailBag)
                .AnyAsync(t => t.Barcode.Equals(barcode) &&
                t.MailBagItems.FirstOrDefault() != null && 
t.MailBagItems.FirstOrDefault().MailBag.Number.ToLower().Equals(mailbagNumber.ToLower()));

For some reason, I'm getting the following exception:出于某种原因,我收到以下异常:

System.InvalidOperationException: The LINQ expression could not be translated. System.InvalidOperationException:无法翻译 LINQ 表达式。 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().以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估。

I know for a fact from removing parts of the boolean expression that the issue is in the last boolean condition where I'm checking the mailbag number.我通过删除 boolean 表达式的一部分知道一个事实,即问题出在最后一个 boolean 条件中,我正在检查邮袋编号。 However, I get the same error if I remove the calls to ToLower().但是,如果我删除对 ToLower() 的调用,我会得到同样的错误。 Can someone indicate what is wrong with my expression and how to fix it?有人可以指出我的表达有什么问题以及如何解决吗? Please note I'm using .NET core 3 and SQL Server.请注意,我使用的是 .NET 核心 3 和 SQL 服务器。

Managed to make the query work by changing it to the following:通过将查询更改为以下内容来管理查询:

var exists = dbcontext.Items
                .AnyAsync(t => t.Barcode.Equals(barcode) &&
                            t.MailBagItems.Any(t => t.MailBag.Number.ToLower().Equals(mailbagNumber.ToLower())));

Seems it wasn't enjoying the.FirstOrDefault().MailBag before.似乎它以前不喜欢 the.FirstOrDefault().MailBag。

Your AnyAsync is to complex for EF to transform to SQL, if you want to still use that query you will have to materialize the entities first, like this:您的AnyAsync对于 EF 转换为 SQL 来说太复杂了,如果您仍想使用该查询,则必须先实现实体,如下所示:

var exists = dbcontext.Items
                .Include(t => t.MailBagItems)
                .ThenInclude(mt => mt.MailBag)
                .ToListAsync()
                .AnyAsync(t => t.Barcode.Equals(barcode) &&
                t.MailBagItems.FirstOrDefault() != null && 
t.MailBagItems.FirstOrDefault().MailBag.Number.ToLower().Equals(mailbagNumber.ToLower()));

Also you are missing the await keyword, or was that intended?您还缺少await关键字,还是有意的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM