[英]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.