我正在尝试使用搜索查询数组基于多列过滤表中的值。我的
SearchQuery
属性如下所示:
public string[] SearchQuery { get; set; }
这是我编写的 LINQ 查询:
.Where(x => request.SearchQuery == null || request.SearchQuery
.Any(searchQuery => string.IsNullOrEmpty(searchQuery) ||
(x.Column1 != null && x.Column1 .Contains(searchQuery)) ||
(x.Column2 != null && x.Column2 .Contains(searchQuery)) ||
(x.Column3 != null && x.Column3 .Contains(searchQuery))
))
但是,在执行此查询时,出现以下错误:
无法翻译 LINQ 表达式“my-expression”。以可翻译的形式重写查询,或者通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用来显式切换到客户端计算。请参阅 https://go.microsoft.com/fwlink/?linkid=2101038 了解更多信息。
我正在使用
IRepository
模式,并且我的查询封装在规范类中。下面是实现的样子:
public sealed class ListItemsSpecification : Specification<Table>
{
public ListItemsSpecification(MyRequest request, bool applyPagination = true)
{
Query
.Where(x => request.SearchQuery == null || request.SearchQuery
.Any(searchQuery => string.IsNullOrEmpty(searchQuery) ||
(x.Column1 != null && x.Column1.Contains(searchQuery)) ||
(x.Column2 != null && x.Column2.Contains(searchQuery)) ||
(x.Column3 != null && x.Column3.Contains(searchQuery))
))
.AsNoTracking();
if (applyPagination)
Query.ApplyListRequest(request.OrderBy, request.Sort, request.Offset, request.Limit);
}
}
如何重写此查询,以便 Entity Framework Core 可以翻译它?
我也尝试单独形成查询,但不幸的是,这种方法也导致了同样的错误
此子句
x => request.SearchQuery == null
可以从 linq 中删除并放置在 if
语句之外。您还尝试在 linq 内循环 request.SearchQuery
,这可能是令人困惑的地方,您可以这样做;
public ListItemsSpecification(MyRequest request, bool applyPagination = true)
{
if (request.SearchQuery != null)
{
Query
.Where(
x.Column1.Contains(request.SearchQuery) ||
x.Column2.Contains(request.SearchQuery) ||
x.Column3.Contains(request.SearchQuery)
)
.AsNoTracking();
}
if (applyPagination)
Query.ApplyListRequest(request.OrderBy, request.Sort, request.Offset, request.Limit);
}
如果
x.Column N
可为空,则执行
public ListItemsSpecification(MyRequest request, bool applyPagination = true)
{
if (request.SearchQuery != null)
{
Query
.Where(
x.Column1 != null && x.Column1.Contains(request.SearchQuery) ||
x.Column2 != null && x.Column2.Contains(request.SearchQuery) ||
x.Column3 != null && x.Column3.Contains(request.SearchQuery)
)
.AsNoTracking();
}
if (applyPagination)
Query.ApplyListRequest(request.OrderBy, request.Sort, request.Offset, request.Limit);
}