2012-07-26 110 views
1

我試圖在Linq中的相同查詢中獲取類別列表和他們的項目。 類似於類別項目清單和相關產品清單。獲取類別和此類別中的項目列表

像項目的示例列表:

Class MyClass { 
Category food; 
List<Product> products; //here I want to get list of products in this category 
} 

而且我有他們之間的連接包含產品ID和類別ID表。

我應該使用哪個查詢來獲得此結果?


編輯:示例的表:

表:產品

  • 的productId
  • PRODUCTNAME
  • productDesc
  • productContent

表:ProductsCategories

  • 的productId
  • 的categoryId

表:類別

  • 的categoryId
  • categoryTitle
  • categoryDe​​sc

回答

0

嘗試這樣:(未經測試)

var q = from pc in ProductsCategories 
     from cat in Categories 
     where pc.productId == cat.categoryId 
     from prod in Products 
     where prod.productId == pc.productId 
     select new { category = cat, product = prod }; 
var q2 = from product in q 
     group product by product.categoryId into g 
     select new { categoryId = g.Key, products = g }; 
+0

問題是沒有辦法在沒有連接它們的表的情況下獲得產品的類別標識。我認爲需要加入,但是我找不到這樣做的方法...... – David 2012-07-26 23:22:41

+0

如果您想要加入表格的幫助,則需要告訴我們關於需要幫助的表格的一些信息。向我們展示您的表格模式。 – dthorpe 2012-07-26 23:54:56

+0

我添加了表格的例子。我希望這將有所幫助。 – David 2012-07-28 14:22:03

0

有產品和類別之間的許多一對多的關係。沒有明確編碼的連接查詢這種關係的一種非常便利的方式是:

from c in Categories 
select new MyClass { 
    Category = c, 
    Products = c.ProductCategories.Select (pc => pc.Product).ToList() 
}