【问题标题】:Linq query with two many-many relationships具有两个多对多关系的 Linq 查询
【发布时间】:2011-07-11 09:55:23
【问题描述】:

我设置了以下要查询的实体:

  • 商店
  • 存储能力。一家商店可以有多种功能(例如,卖巧克力、很大)——但不是必须具备的。
  • 优惠。报价可能需要多个商店功能才能生效,但没有要求。

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

所以涉及到五个表。

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

  • 给定一个报价,一个有效的商店列表
  • 给定一家商店,提供可用优惠列表

使用 SQL 可以从 Store 连接到 StoreCapability,再到 Offer,然后按 offer 和 store 进行分组,并且只获得 count() 等于 offer 的要求数量的 store。但是我不知道从哪里开始使用 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; }
}

【问题讨论】:

  • 你能用sql写例子或查询你想翻译成LINQ吗?
  • 您的意思是您的StoreCapability 链接表被建模为多对多关联而不是实体?
  • 没有 StoreCapability 本身就是一个实体;提供和存储所有权/能力要求都是与此的 m2m 关系。
  • @Piotr Auguscik:添加了一些 sql 示例

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


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多