多对多的关系

时间:2011-09-14 10:09:59

标签: linq many-to-many

我正在尝试编写一个linq来从多个表中获取数据。

以下是表格

产品(ID,名称,描述)

Products_Items(ID,ProductID,Description)

ProductsNeeds(ID,Name)

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;

此查询返回(Products)并且它具有Produts_Items,但它没有ProductsNeeds。

我应该做什么修改才能让每个Products_items拥有ProductsNeeds?

由于

1 个答案:

答案 0 :(得分:0)

最后我找到了解决方案。

更改是返回Product_Items而不是返回Products。

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;