【发布时间】:2021-12-07 15:42:55
【问题描述】:
我正在尝试编写一个半高级的 LINQ to SQL 查询来搜索我在 .NET 6 项目中的实体。我的 LINQ 语句中的过滤看起来像这样:
List<string> _searchList = new() {"%a%", "%b%"};
var _query = (from tblHeader in _DbContext.batches
where tblHeader.isDeleted != true
select tblHeader)
_query = _query.Where(x =>
_searchList.All(y =>
EF.Functions.Like(x.Name, y)
)
);
var _results = await _query.ToListAsync();
错误看起来像:
The LINQ expression 'y => __Functions_1
.Like(
matchExpression: EntityShaperExpression:
FFM.DataAccessModels.App.batches
ValueBufferExpression:
ProjectionBindingExpression: EmptyProjectionMember
IsNullable: False
.Name,
pattern: y)' 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 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
是否可以在 Where() 中使用 LINQ All()(甚至是 linq Any())?或者有没有更好的方法来编写这个查询?
【问题讨论】:
-
对于这个查询,你可以遍历搜索列表并多次执行 Where (它将加入你的 where 条件和)。
-
LINQ to Entities 仅在使用本地集合时支持
Contains。使用this my solution,它将创建所需的SQL。 -
@Evk 这是我当前的解决方案,但是我正在尝试合并能够进行 OR 搜索(即搜索“用户输入 A”或“替代用户输入 B”),匹配每个单词在搜索 1 或搜索 2 中的每个单词。这样,我想要的查询还包含另一个嵌套的 .All() 运算符,但在我的问题中,我将其简化为 if first 开始中断的位置。
-
遗憾的是,没有“内置”支持。您需要手动创建表达式,但您可以使用一些第三方库,例如 LinqKit
-
@Evk 有没有什么方法可以将这种 OR 功能与您最初建议的循环结合起来?
标签: c# linq entity-framework-core linq-to-entities