[英]Entity Framework Linq Where condition With Any/All
使用下面的代碼,我正在嘗試獲取價格范圍為 Linq 的商品列表
public Task<List<Item>> GetFilteredItems(List<Tuple<decimal, decimal>> priceList)
{
var itemList = from i in _dbTable
where (priceList.Count() == 0 || (priceList.All(x => i.MRP >= x.Item1) && priceList.All(x => i.MRP <= x.Item2)))
select i;
return Task.FromResult(itemList.Cast<Item>().ToList());
}
但是出現錯誤
Error creating query string: The LINQ expression 'x => EntityShaperExpression:
GiftCartBO.Entities.ItemTBL
ValueBufferExpression:
ProjectionBindingExpression: EmptyProjectionMember
IsNullable: False
.MRP >= x.Item1' 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..
EF 在內部將您的LINQ
查詢轉換為SQL
查詢。 有時LINQ
查詢的所有部分都無法轉換為SQL
,因此會引發運行時錯誤。 同樣的事情也發生在你身上。 EF 將無法為SQL
查詢轉換List<Tuple<decimal, decimal>>
object。 在錯誤消息https://go.microsoft.com/fwlink/?linkid=2101038中提供的錯誤消息和鏈接中提到了同樣的事情。
您可以一次獲取所有數據,然后像下面這樣應用您的LINQ
查詢。
var itemList = _dbTable.ToList()
.Where(i => priceList.Count() == 0 || (priceList.All(x => i.MRP >= x.Item1) && priceList.All(x => i.MRP <= x.Item2)));
return Task.FromResult(itemList.Cast<Item>().ToList());
如果您發現上述查詢返回正確的結果,那么您應該按照@Robert Harvey 在評論中的建議改進您的代碼。 您可以獲取item1
的max
和item2
的min
並使用它。 完整的代碼 cab 如下所示。
if (priceList.Count() == 0)
{
var itemList = _dbTable.ToList();
return Task.FromResult(itemList.Cast<Item>().ToList());
}
else
{
var maxItem1 = priceList.Max(x => x.item1);
var minItem2 = priceList.Min(x => x.item2);
var itemList = _dbTable.ToList()
.Where(i => i.MRP >= maxItem1 && i.MRP <= minItem2);
return Task.FromResult(itemList.Cast<Item>().ToList());
}
我相信您想獲取所有價格介於priceList
的任何一個值之間的記錄。 然后您需要像下面這樣更新您的查詢。
var itemList = _dbTable.ToList()
.Where(i => priceList.Count() == 0 || priceList.Any(x => i.MRP >= x.Item1 && i.MRP <= x.Item2));
return Task.FromResult(itemList.Cast<Item>().ToList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.