gpt4 book ai didi

c# - 使用 Linq + Include 排序

转载 作者:太空狗 更新时间:2023-10-29 23:32:44 25 4
gpt4 key购买 nike

我与两个实体有一对多关系:

Order:
int OrderId
string OrderNumber
...

OrderItem:
int ItemId
int sequence
...

Product:
int ProductId
string ProductName

ProductType:
int ProductTypeid
string Title

一个 Order 有多个 OrderItems,每个 OrderItem 有一个 Product 和每个 Product 有一个 ProductType

我想编写一个 Linq,它返回所有订单及其 itemsProductProductType 并且项目按序列字段排序。如何编写查询,例如以下查询?

Order by with Linq 的帮助下我写了这个查询:

var myOrder= db.Orders.Include("OrderItems")
.Where(x => x.OrderId == 3)
.Include("OrderItems.Product")
.Include("OrderItems.Product.ProductType")
.Select(o => new {
order = o,
orderItems = o.OrderItems.OrderBy(i => i.sequence)
}).FirstOrDefault();

但是当它返回结果时,它不包含 Product 和 ProductType 数据。我的错误在哪里?

最佳答案

您需要先将所有调用放在 Include() 中。这应该有效:

var myOrder= db.Orders.Include("OrderItems")
.Include("OrderItems.Product")
.Include("OrderItems.Product.ProductType")
.Where(x => x.OrderId == 3)
.Select(o => new {
order = o,
orderItems = o.OrderItems.OrderBy(i => i.sequence)
}).FirstOrDefault();

另外,当您有 .Include("OrderItems.Product.ProductType") 时,您不需要 .Include("OrderItems")。 Include("OrderItems.Product"),因为它将在包含产品类型的过程中包含 OrderItems 及其产品。它必须这样做,否则您将无法在代码中导航到它们 - 它会将它们附加到什么?

在这种情况下,这似乎可以解释它:http://wildermuth.com/2008/12/28/Caution_when_Eager_Loading_in_the_Entity_Framework

你可以在不使用 includes 的情况下绕过:

var query = db.Orders
.Where(x => x.OrderId == 3)
.Select(o => new {
order = o,
orderItems = o.OrderItems.OrderBy(i => i.sequence),
products = o.OrderItems.Select(i => new { i, i.Product, i.Product.ProductType })
});

您转换到输出选择中的任何内容都将自动预先加载。像这样的预加载实际上在某些方面更可取,因为您只是实现了您需要的东西,而不是完整的对象图。 (尽管在这种情况下,我们实现的与 include 实现的相同。)

关于c# - 使用 Linq + Include 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14477389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com