2009-11-30 53 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

相關問題