2011-09-14 138 views
0

我想寫一個linq從多個表中獲取數據。多對多的關係

下面是表

產品(ID,名稱,說明)

Products_Items(ID,產品ID,說明)

ProductsNeeds(ID,姓名)

ProductsItems_Needs(的ItemID, NeedsID)

這是t-sql查詢

select gPro.Name,gProItems.ShortDescription,gProItems.Description,gNeeds.Name 
from Products gPro 
join Products_Items gProItems on gPro.ID = gProItems.ProductID 
join ProductsItems_Needs gProNeeds on gProNeeds.ItemID = gProItems.ID 
join ProductsNeeds gNeeds on gNeeds.ID = gProNeeds.NeedsID 
where gProItems.ID = 1 

這是LINQ

var q = from p in objM.Products 
     join gpItems in objM.Products_Items on p.ID equals gpItems.ProductID 
     from needs in gpItems.ProductsNeeds 
     where gpItems.ID == 1 
     select p; 

該查詢將返回(產品)和它有Produts_Items但它不是ProductsNeeds。

我應該做些什麼修改才能使每個Products_items具有ProductsNeeds?

謝謝

回答

0

最後我找到了解決方案。

變化是,不是返回Products返回Product_Items。

var q = from pItems in objM.Products_Items 
join p in objM.Products on pItems.ID equals p.ID into joinedProducts 
    from p in joinedProducts.DefaultIfEmpty() 
from needs in pItems.ProductsNeeds 
where pItems.ID == 1 
select pItems;