EF 4 Count()选项性能

时间:2012-01-05 03:35:52

标签: entity-framework-4.1

使用EF 4.1计算表格中项目的最佳效果是什么?

this.context.MyTable.Count(x.idTenant == 5);

 this.context.MyTable.Where(x.idTenant == 5).Count();

计算表中实体的任何其他方法,是否更高效?

2 个答案:

答案 0 :(得分:1)

LINQPad中尝试这样做表明生成的sql是相同的:

var r1 = Users.Count(u => u.JurisdictionId == 5).Dump();    
var r2 = Users.Where(u => u.JurisdictionId == 5).Count().Dump(); 

和生成的sql:

SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT 
    COUNT(1) AS [A1]
    FROM [System].[Users] AS [Extent1]
    WHERE 5 = [Extent1].[JurisdictionId]
)  AS [GroupBy1]
GO

SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT 
    COUNT(1) AS [A1]
    FROM [System].[Users] AS [Extent1]
    WHERE 5 = [Extent1].[JurisdictionId]
)  AS [GroupBy1]

这是使用EF 4.2,但这在4.1中应该是相同的。

答案 1 :(得分:1)

根据Linq的输出,表达式在它们生成的SQL中是相同的:

SELECT COUNT(*) AS [value]
FROM [MyTable] AS [t0]
WHERE [t0].[idTenant] = @p0