2009-11-30 35 views
4

假设我有一个Boxes列表,并且在一个框中可以有多个项目。如何使用LINQ-to-Entity通过包含的对象进行查询

  • 盒(ID)
  • 项目(ID,boxId)

我试图建立的LINQ to实体的查询,可以返回所有包含了所有规定的项目的复选框。

List<Box> FindBoxContainingAllSpecifiedItems(List<int> itemIds) 
{ 
    var q = from box in ctx.Boxes 
      where ??? 
} 

感谢您的帮助

回答

0

这里是我发现由于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(); 

} 
+0

让我知道你们对这个解决方案的看法 – pdiddy 2009-12-01 14:04:21

4

这取决于箱子的实现。但让我们暂时说它有一个IEnumerable<int>类型的属性项目。在这种情况下,你可以使用相交扩展方法,看的项目都占

var q = from box in ctx.Boxes 
     where box.Items.Intersect(itemIds).Count() == itemIds.Count; 
+0

啊谢谢,我会尝试了这一点 – pdiddy 2009-11-30 21:49:38

+0

如果我没有thie IEnumerable的但IEnumerable的 ......? – pdiddy 2009-11-30 22:00:31

+0

@pdiddy,项目的API是什么? – JaredPar 2009-11-30 22:24:48