Linq查询获取Child的子记录

时间:2010-10-13 13:14:59

标签: linq

在我的父子方案中,我需要获得所有客户的自定义列表及其订单总数和订单项。

客户可以拥有多个订单,订单可以包含许多OrderItem。我需要编写一个查询,它返回实体对象的集合,该对象具有该Customer对象的Customer Entity和Total Orders以及Total OrderItem,例如

var result = from c in  ctx.Customers
         from o in  ctx.Orders
         from d in  ctx.OrderItems
         select new List<CustomerVM()
         {
            customer = c,
            totalOrders = o.Count,
            totalOrderItems = XXXX  
         }  
public class CustomerVM {
 public Customer customer {get; set;}
 public int totalOrders {get; set;}
public int totalOrderItems {get; set;}
}

我该怎么做?

1 个答案:

答案 0 :(得分:3)

您需要使用SelectMany

var result = (from c in ctx.Customers
              select new CustomerVM
              {
                  customer = c,
                  totalOrders = c.Orders.Count(),
                  totalOrderItems = c.Orders.SelectMany(o => o.OrderItems).Count()
              }).ToList();