用Linq + Include排序

Mas*_*oud 5 c# linq include

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

Order:
int OrderId 
string OrderNumber
...

OrderItem:
int ItemId
int sequence
...

Product:
int ProductId
string ProductName

ProductType:
int ProductTypeid
string Title
Run Code Online (Sandbox Code Playgroud)

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

我想编写返回所有订单他们一个LINQ itemsProductProductType和物品通过序列字段进行排序。如何编写查询,例如以下查询?

与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();
Run Code Online (Sandbox Code Playgroud)

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

Ben*_*thy 4

您需要将所有呼叫放在第一位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();
Run Code Online (Sandbox Code Playgroud)

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

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

您可以在不使用 include 的情况下绕过:

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 })
});
Run Code Online (Sandbox Code Playgroud)

您投影到输出选择中的任何内容都将自动预先加载。像这样的预加载实际上在某些方面更可取,因为您只是具体化了您需要的内容,而不是完整的对象图。(尽管在本例中我们实现的内容与包含内容相同。)