使用Entity Framework连接2个表并检索table1中每个记录的table2中的前X个记录

时间:2016-11-23 11:30:31

标签: c# entity-framework

我尝试使用Entity Framework完成看似非常简单的任务。我有两个小的SQL表:Customers (Id, Name)Orders (Id, CustomerId, DateTime)。我需要从数据库中获取数据,并为每个客户显示一个包含所有客户和前10个订单(或者如果客户少于10个订单的所有订单)的表格。

很明显,如何以简单的方式获取所需数据:通过1个查询(var customers = dc.Customers.ToList()),获取所有客户,然后进行foreach循环以检索每个客户的订单:

var dic = new Dictionary<Customer, List<Order>>();
foreach (var customer in customers)
{
    dic.Add(customer, dc.Orders.Where(o => o.CustomerId == customer.Id).OrderBy(o => o.DateTime).Take(10).ToList();
}

但这种方式使用了太多的数据库查询。如何仅使用1个DB查询来获得相同的结果?

1 个答案:

答案 0 :(得分:1)

您可以使用

Dictionary<Customers, List<Orders>> dic = dc.Customers.Join(dc.Orders.OrderBy(o => o.DateTime).Take(10),
                            c => c.Id,
                            o => o.CustomerId,
                            (c, o) => new { Customers = c, Orders = o }
                            )
                            .GroupBy(x => x.Customers)
                            .ToDictionary(x => x.Key, x => x.Select(y=>y.Orders)

                                                            .ToList());

左加入

Dictionary<Customers, List<Orders>> dic = (from c in Customers
                                                      join o in Orders.OrderBy(o => o.DateTime).Take(10) on c.Id equals o.CustomerId into j1
                                                      from j2 in j1.DefaultIfEmpty()
                                                      group j2 by c into grouped
                                                      select new { Customers = grouped.Key, Orders = grouped.ToList() })
                                                     .ToDictionary(x => x.Customers, x => x.Orders);