Linq查询有两个很多关系

时间:2011-07-11 09:55:23

标签: c# sql linq entity-framework linq-to-entities

我设置了以下实体,我试图查询:

  • 存储
  • StoreCapability。商店可以有多种功能(例如卖巧克力,很大) - 但不需要有任何功能。
  • 优惠。优惠可能需要多个商店功能才能生效,但不需要任何要求。

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

所以涉及五个表。

我希望能够使用linq获得以下内容:

  • 给出要约,
  • 有效的商店列表
  • 鉴于商店,可用优惠清单

使用SQL可以从Store,StoreCapability加入Offer,然后按要约和商店分组,只获得count()等于商品要求数量的商店。但是我不知道从哪里开始使用Linq,因为Entity框架隐藏了许多表。任何人都可以帮我解决这个问题吗?

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; }
}

1 个答案:

答案 0 :(得分: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;