0

What is the most performant way to count items on a table using EF 4.1?

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

or

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

Any other way to Count entities in a table, being it more performant?

Romias
  • 13,783
  • 7
  • 56
  • 85
  • I don't know enough to answer, but your two examples would must likely create the same expression tree. – Joe Jan 05 '12 at 03:39
  • http://stackoverflow.com/questions/890381/how-to-count-rows-within-entityframework-without-loading-contents – Jayantha Lal Sirisena Jan 05 '12 at 03:40
  • @JoeTuskan, Reshaper suggested the first one, but I don't know if it is just another way to write it or there is a performance gain. – Romias Jan 05 '12 at 03:42

2 Answers2

1

Trying this in LINQPad shows the sql generated to be the same:

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

and the sql generated:

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]

This is using EF 4.2, but this should be the same in 4.1.

Jeff Ogata
  • 56,645
  • 19
  • 114
  • 127
1

According to the output from Linq, the expressions are equal in the SQL they generate:

SELECT COUNT(*) AS [value]
FROM [MyTable] AS [t0]
WHERE [t0].[idTenant] = @p0
Joe
  • 80,724
  • 18
  • 127
  • 145