【问题标题】:Linq To Entities Indirect Contextual Table Join in Fluent APILinq To Entities Indirect Contextual Table Join in Fluent API
【发布时间】:2017-02-28 22:55:56
【问题描述】:

我正在使用纯 Fluent API 代码优先。我不在我的实体上使用属性,我将我的上下文分开。我有一个OrderEntity,它与OrderDetails 具有一对多关系,并由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

和 Linq:

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 的价格时,OrderItemPrice 之间存在间接关系。

我所有的其他 LINQ 都很漂亮,并且可以正确使用导航属性等。有没有办法在 Fluent API 中定义这种上下文关系并在我的 LINQ 有 Order -> Detail -> Item -> Price 时使用它?还是我每次都必须手动定义关系?

【问题讨论】:

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


    【解决方案1】:

    将我的 SQL 大脑应用到 Linq,我记得大多数简单的 Join 可以移动到 WHERE 子句中。因此,虽然这无助于在 Fluent API 中定义 Order 和 ItemPrices 之间的上下文关系,但它确实允许我使用干净的 Linq 而无需像这样的 Join:

    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 查询满足了我依赖导航属性而不是连接的需要。

    【讨论】:

      猜你喜欢
      • 2010-10-25
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 2017-03-31
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      相关资源
      最近更新 更多