Romias
Romias

Reputation: 14133

EF 4 Count() options performance

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?

Upvotes: 0

Views: 733

Answers (2)

Joe
Joe

Reputation: 82604

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

Upvotes: 1

Jeff Ogata
Jeff Ogata

Reputation: 57783

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.

Upvotes: 1

Related Questions