想象一下选择至少有两个订单的客户。如何以高性能的方式使用实体框架来表达这一点?
context.Customers.Where(c => c.Orders.Count() > 1)
这个看似无辜的表达式导致 SQL 类似:
SELECT
[Project1].[Id] AS [Id]
FROM ( SELECT
[Extent1].[Id] AS [Id],
(SELECT
COUNT(1) AS [A1]
FROM [dbo].[Orders] AS [Extent2]
WHERE [Extent1].[Id] = [Extent2].[UserId]) AS [C1]
FROM [dbo].[Customers] AS [Extent1]
) AS [Project1]
WHERE [Project1].[C1] > 1
SQL Server 是否足够聪明,可以避免计算每个实体的连接的完整计数,还是应该使用不同的方法?
除了简单地运行查询和测试响应时间之外,我将如何对此进行测试?
以下是我考虑过的其他一些查询表达式。简单的测试显示它们之间的性能差异很小。
context.Customers.Where(c => c.Orders.Take(2).Count() > 1)
context.Customers.Where(c => c.Orders.OrderBy(o => o.Id).Skip(1).Any())
context.Orders.GroupBy(l => l.Customer).Where(g => g.Count() > 1).Select(g => g.Key)