gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:34 25 4
gpt4 key购买 nike

我正在尝试使用 Entity Framework 完成看似非常简单的任务。我有 2 个小型 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 个数据库查询来获得相同的结果?

最佳答案

你可以使用

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);

关于c# - 使用 Entity Framework 连接 2 个表并为 table1 中的每条记录检索 table2 中的前 X 条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40763324/

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