She*_*jid 33 c# linq entity-framework .net-core
我有 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();
}
Run Code Online (Sandbox Code Playgroud)
每当执行此表达式时,我都会收到以下错误
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."
Run Code Online (Sandbox Code Playgroud)
我无法添加 ToList() 并切换到客户端评估,因为数据集太大而无法这样做。
请告知我如何在不切换到客户评估的情况下解决此问题。
谢谢
Ste*_* Py 32
问题是,您尝试在表达式string.Contains
中执行 a 操作Any
,而 EF 会因尝试组合为 SQL 而窒息。Ceptus 位于鼻子上,为子句构建谓词或对Where
术语比较进行 OR 运算。否则,您的代码应该在没有包含检查的情况下工作,而是进行相等检查:
没有Contains
: ( 相等检查而不是LIKE %name%
)
var terms = title.Split(' ').ToList();
items = items.Where(w => terms.Contains(w.ItemName)); // IN clause.
Run Code Online (Sandbox Code Playgroud)
构建表达式:
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);
Run Code Online (Sandbox Code Playgroud)
因此,对于标题中的每个术语,我们在 ItemName 上使用 LIKE %term% 进行 OR 匹配。
归档时间: |
|
查看次数: |
116835 次 |
最近记录: |