我正在嘗試撰寫一個半高級的 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())?或者有沒有更好的方法來撰寫這個查詢?
uj5u.com熱心網友回復:
因為您想要的解決方案是 _searchList 中與查詢匹配的所有專案可以Where使用回圈為 _searchList 中的每個專案使用子句重寫,結果仍然是單個查詢。
List<string> _searchList = new() {"%a%", "%b%"};
var _query = _DbContext.batches.Where(x => !x.isDeleted);
foreach(var searchItem in _searchList)
_query = _query.Where(x => EF.Functions.Like(x.Name, searchItem);
var _results = await _query.ToListAsync();
uj5u.com熱心網友回復:
使用此我對擴展方法的答案FilterByItems。然后您可以執行以下操作:
List<string> _searchList = new() {"%a%", "%b%"};
var _query =
from tblHeader in _DbContext.batches
where tblHeader.isDeleted != true
select tblHeader;
_query = _query
.FilterByItems(_searchList, (x, y) => EF.Functions.Like(x.Name, y), true);
var _results = await _query.ToListAsync();
uj5u.com熱心網友回復:
你不能這樣做嗎?
var result = _DbContext.batches
.Where(tblHeader => tblHeader.isDeleted != true)
.Where(x => _searchList.All(y => EF.Functions.Like(x.Name, y))
.ToListAsync();
編輯:
喜歡查詢支持通配符,我想你需要匹配包含'a'和'b'的所有結果,所以你可以使用:“[ab]%”。
var result = _DbContext.batches
.Where(tblHeader => tblHeader.isDeleted != true)
.Where(x => EF.Functions.Like(x.Name, "[ab]%"))
.ToListAsync();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/350321.html
上一篇:Linqwhere條件奇怪
