选择至少存在N个连接实体的位置

时间:2012-08-04 16:37:02

标签: sql-server performance entity-framework

想象一下,选择至少有两个订单的客户。如何以高效的方式使用Entity Framework表达它?

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)

0 个答案:

没有答案