[英]The LINQ expression could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation
I have C# application (.NET Core 3.1) and I have written the following LINQ expression.我有 C# 应用程序(.NET Core 3.1)并且我编写了以下 LINQ 表达式。
public ActionResult<bool> GetItems(string title)
{
var items = _service.All.GetItems().OrderByDescending(o => o.Id).Where(w => w.Portal_Id == 1);
if (!string.IsNullOrWhiteSpace(title))
{
var terms = title.Split(' ').ToList();
items = items.Where(w => terms.Any(a => w.ItemName.Contains(a)));
}
// Some Other code
return Ok();
}
whenever this expression is executed i get the following error每当执行此表达式时,我都会收到以下错误
The LINQ expression 'DbSet<PosItem>\r\n .Where(p => !(p.IsDeleted))\r\n
.OrderByDescending(p => p.CreatedAt)\r\n .Where(p => p.Portal_Id == 1)\r\n .Where(p => __terms_1\r\n
.Any(a => p.ItemName.Contains(a)))' 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().
See https://go.microsoft.com/fwlink/?linkid=2101038 for more information."
I cannot add ToList() and switch to client evaluation because the data set is too big to do so.我无法添加 ToList() 并切换到客户端评估,因为数据集太大而无法这样做。
Please advise how can I resolve this issue without switching to client evaluation.请告知如何在不切换到客户评估的情况下解决此问题。
Thanks谢谢
The issue is that you are trying to do a string.Contains
within an Any
expression which EF will choke on trying to compose down to SQL.问题是您正在尝试在Any
表达式中执行string.Contains
,EF 在尝试组合成 SQL 时会窒息。 Cleptus is on the nose, to build a predicate for the Where
clause OR-ing the term comparisons. Cleptus 正准备为Where
子句构建一个谓词 OR-ing 术语比较。 Otherwise your code should work without the contains check, but rather an equality check:否则,您的代码应该可以在没有包含检查的情况下工作,而是进行相等性检查:
Without Contains
: (equality check rather than LIKE %name%
)不Contains
:(相等检查而不是LIKE %name%
)
var terms = title.Split(' ').ToList();
items = items.Where(w => terms.Contains(w.ItemName)); // IN clause.
Built expression:内置表达式:
var terms = title.Split(' ').ToList();
Expression<Func<Item, bool>> predicate = (Item) => false;
foreach(var term in terms)
predicate = predicate.Or(x => x.ItemName.Contains(term));
items = items.Where(predicate);
So for each term in the title, we OR a match using a LIKE %term% on the ItemName.因此,对于标题中的每个术语,我们在 ItemName 上使用 LIKE %term% 进行 OR 匹配。
This problem can also occur when using multiple ParameterExpression in one single Expression.在一个表达式中使用多个 ParameterExpression 时,也会出现此问题。 Always transmit den ParameterExpression instance to all Expression.Property(argPara, "Name") values.始终将 den ParameterExpression 实例传输到所有 Expression.Property(argPara, "Name") 值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.