[英]How to use LINQ-to-Entity to query by contained objects
假设我有一个盒子列表,在一个盒子里你可以有多个项目。
我正在尝试构建一个linq to entity查询,它可以返回包含所有指定项的所有框。
List<Box> FindBoxContainingAllSpecifiedItems(List<int> itemIds)
{
var q = from box in ctx.Boxes
where ???
}
谢谢您的帮助
这取决于盒子的实施。 但是暂时让我们说它有一个IEnumerable<int>
类型的属性Items。 在这种情况下,您可以使用Intersect扩展方法来查看是否全部考虑了这些项目
var q = from box in ctx.Boxes
where box.Items.Intersect(itemIds).Count() == itemIds.Count;
由于JaredPar的贡献,我发现了这一点。
List<Location> FindLocationContainingAllItems(List<int> itemIds)
{
var itemQuery = from item in ctx.Items
select item;
// Workaround the Where In Clause (http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/095745fe-dcf0-4142-b684-b7e4a1ab59f0)
itemQuery = itemQuery.Where(BuildContainExpression<Items, int>(i=> i.Id, itemIds));
int itemCount = itemIds.Count();
var locQuery = from loc in ctx.Locations
from box in loc.Boxes
where (from items in box.Items select items).Intersect(itemQuery).Count == itemCount
select loc;
return locQuery.ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.