如何在EF7中延迟加载多个级别时前10名

时间:2016-03-16 13:46:46

标签: c# sql entity-framework linq entity-framework-core

例如,我有一个简单的域名模型 Customer > 订单订单> Orderlines

我想获得所有客户的清单,每个客户都有最近的10个订单,包括订单行。

以下LINQ不起作用(这不是一个完全的惊喜),但如果可能的话,应该是正确的语法?

var customers = _context.Customers
            .Include(c => c.Orders)
                 .OrderByDescending(c => c.CreatedDateTime)
                 .Take(10)
                 .ThenInclude(c => c.OrderLines);

生成的SQL从客户(而不是订单的TOP(10))获取TOP(10)。然后从最终结果ORDERBY DESC。所以OrderByDescending和Take(10)适用于Customers not Orders。

更新

以下代码(没有ThenInclude)

var customers = _context.Customers
                 .Include(c => c.Orders)
                 .OrderByDescending(c => c.Created)
                 .Take(10)

生成以下SQL ..

SELECT [a].[Id], [a].[CreatedDateTime], [a].[CustomerID]
FROM [Order] AS [a]
INNER JOIN (
    SELECT DISTINCT TOP(10) [c].[CreatedDateTime], [c].[Id]
    FROM [Customer] AS [c]
) AS [c] ON [a].[CustomerID] = [c].[Id] ORDER BY [c].[CreatedDateTime] DESC, [c].[Id]

这显然不是我想要的。

3 个答案:

答案 0 :(得分:0)

我显然无法测试这个,但你不需要使用Count吗?

var customers = _context.Customers
            .Include(c => c.Orders)
                 .OrderByDescending(c => c.CreatedDateTime)
                 .ThenInclude(c => c.OrderLines).Take(10);

答案 1 :(得分:0)

试试这个

 var customers = from n in _context.Customers
                    select
                        new
                        {
                            n,
                            Orders = _context.Orders.Where(l => l.CustomeId == 
                             n.CustomeId).OrderByDescending(l => l.Date).Take(10)
                        };

答案 2 :(得分:0)

您希望将订单和TOP应用于订单,因此请在订单而不是客户上调用方法:

var customers = _context.Customers
        .Include(c => c.Orders
             .OrderByDescending(c => c.CreatedDateTime)
             .Take(10)
             .Include(c => c.OrderLines));