Linq To Entities间接上下文表加入Fluent API

时间:2017-02-28 22:55:56

标签: c# entity-framework linq ef-fluent-api

我使用纯粹的Fluent API Code-First。我没有在我的实体上使用属性,而是保持我的上下文分离。我有OrderEntityOrderDetails有一对多的关系,由OrderID加入。因此,我有一个EntityTypeConfiguration<OrderDetailEntity>,其中包含以下内容:

HasRequired(x => x.Order).WithMany(x => x.Details);
HasRequired(x => x.Item);

物品与其价格有关系。但这种关系是笛卡尔式的。一个项目有200 + ItemPrices与之关联。 ItemPrice看起来像这样:

public string CurrencyCode { get; set; }
public int PriceTypeID { get; set; }
public decimal Price { get; set; }

有3 PriceTypes和几十种货币。

我认为ItemPrice适合定义Item和ItemPrice之间的关系是这样的:

HasRequired(x => x.Item).WithMany(x => x.ItemPrices);

商品具有货币代码或Price类型。商品只是一个商品,货币代码和价格类型是在放置Order时确定的。这两个变量在订单上。因此,为了确定订单的价格,我有这个:

SQL:

SELECT *
FROM Orders o
INNER JOIN OrderDetails od ON o.OrderID = od.OrderID
INNER JOIN Items item ON od.ItemID = item.ItemID
INNER JOIN ItemPrices itemPrice ON item.ItemID = itemPrice.ItemID AND o.CurrencyCode = itemPrice.CurrencyCode AND o.PriceTypeID = itemPrice.PriceTypeID

林奇:

context.Orders
.Join(context.OrderDetails,
    o => o.OrderID,
    od => od.OrderID,
    (o, od) => new { o, od })
.Join(context.Items,
    o2od => o2od.od.ItemID,
    item => item.ItemID,
    (o2od, item) => new { o2od, item })
.Join(context.ItemPrices,
    o2od2item => new { o2od2item.item.ItemID, o2od2item.o2od.o.CurrencyCode, o2od2item.o2od.o.PriceType },
    itemPrice => new { itemPrice.ItemID, itemPrice.CurrencyCode, itemPrice.PriceType },
    (o2od2item, itemPrice) => new { o2od2item, itemPrice })

长篇短篇:在计算Order&#39;的背景下,ItemPriceOrder之间存在间接关系。价格。

我的所有其他LINQ都很漂亮,并正确使用导航属性等。有没有办法在Fluent API中定义这种上下文关系,并在我的LINQ具有Order时使用它 - &gt;细节 - &gt;项目 - &gt;价钱 ?或者我每次都必须手动定义这种关系?

1 个答案:

答案 0 :(得分:1)

将我的SQL大脑应用于Linq,我记得大多数简单的联接可以移动到WHERE子句中。因此,虽然这对于在Fluent API中定义Order和ItemPrices之间的上下文关系没有帮助,但它确实允许我使用没有连接的干净Linq,如下所示:

context.Orders
.Where(x => orderIDs.Contains(x.OrderID)
    && x.Details.Any(y => 
        y.Item.ItemPrices.Any(z =>
            && z.CurrencyCode == x.CurrencyCode 
            && z.PriceType == x.PriceType
    )))

虽然我宁愿描述不同上下文中表之间的关系,但这个LINQ查询满足了我依赖导航属性而不是连接的需要。