2011-07-11 49 views
0

我有以下的實體成立,我正在嘗試查詢:Linq查詢有兩個多對多的關係

  • 商店
  • StoreCapability。一家商店可以有多種功能(例如出售巧克力,很大) - 但不一定要有。
  • 優惠。要約可能需要多個商店功能才能生效,但不需要任何要求。

Store -[m2m]- StoreCapability -[m2m]- Offer

所以有涉及五個表。

我希望能夠獲得以下使用LINQ:

  • 給出一個報價,商店的列表,它的有效期爲
  • 鑑於商店,可
  • 的報價列表

使用SQL將有可能從商店的加入,StoreCapability,通過提供和存儲所提供的,然後組,只有獲得具有計數()等於要求的提議具有數家門店。但是我不知道在哪裏這個LINQ的開始,因爲多對多表由實體框架隱離我而去。請任何人都可以幫助我如何做到這一點?

的SQL可能會與此類似:

SELECT Offers.Id, offers.Name, Stores.Id, Stores.Name FROM Offers 
--join to the capabilities that this offer needs 
LEFT OUTER JOIN StoreCapabilityOffers offerRequirements ON Offers.Id = offerRequirements.Offer_Id 
--join to stores which have capability 
LEFT OUTER JOIN StoreCapabilities ON offerRequirements.StoreCapability_Id = StoreCapabilities.Id 
--join to stores 
LEFT OUTER JOIN StoreStoreCapabilities storeCap ON offerRequirements.StoreCapability_Id = storeCap.StoreCapability_Id 
LEFT OUTER JOIN Stores on storeCap.Store_Id = Stores.Id 

GROUP BY Offers.Id, offers.Name, Stores.Id, Stores.Name 
-- get stores who have the right number of capabilities so all requirements are all met 
HAVING COUNT(*) = (
    select COUNT(*) from StoreCapabilityOffers x where x.Offer_Id = Offers.Id 
) 

實體如下:

public class Store 
{ 
    public int Id { get; set; } 
    public virtual ICollection<StoreCapability> Capabilities { get; set; } 
} 

public class StoreCapability 
{ 
    public int Id { get; set; } 
    public virtual ICollection<Store> Stores { get; set; } 
    public virtual ICollection<Offer> Offers { get; set; } 
} 

public class Offer 
{ 
    public int Id { get; set; } 
    public virtual ICollection<StoreCapability> StoreCapabilityRequirements { get; set; } 
} 
+0

你可以在sql中編寫示例或查詢嗎?你想轉換成LINQ嗎? –

+0

你的意思你的'StoreCapability'鏈接表建模爲一個多一對多的關聯,而不是作爲一個整體? – Jodrell

+0

否StoreCapability本身就是一個實體;提供和存儲所有權/需求的能力都與此有關。 –

回答

1

我覺得這樣的事情應該工作:

給出一個報價,商店的列表它是有效的:

var stores = from o in context.Offers 
      from c in o.StoreCapabilityRequirements 
      from s in c.Stores 
      where o.Id == 1 
      select s; 

給定一個商店,可用優惠清單:

var offers = from s in context.Stores 
      from c in s.Capabilities 
      from o in c.Offers 
      where s.Id == 1 
      select o;