Does Linq retrieve all records first if I do a Count?
Assume I have a table called Population that stores some demographic data. In T-SQL, to get the count of people over 50, I might do something like this:
SELECT COUNT(*) FROM POPULATION
WHERE AGE > 50
I thought the following linq statement would work, but it just returns zero and I don't understand why.
var count = _con开发者_如何学Pythontext.Population.Count(x => x.Age > 50);
In order for me to actually get the count, I have to do either of the following:
var count = _context.Populaton.Where(x => x.Age > 50).Count();
var count = _context.Population.Select(x => x.Age > 50).Count();
Why are the above scenarios the case?
Linq does not retrieve all the records first. It defers the execution of the query until last possible moment. This allows the query to be optimized.
http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx
I have found that order is important sometimes. Hope this helps.
Bob
In all cases Count()
will NOT do the computation in memory based on the records returned from the database, but it will actually change the generated SQL to include the COUNT
statement. A simplistic version of your generated TSQL query would be something like:
SELECT
COUNT(1)
FROM [dbo].[Population] AS [Extent1]
WHERE [Extent1].[Age] > 50
When you call Count()
the query is executed immediately. All your queries seem to be correct, so check your database, provider and context to make sure the query is executing properly.
Correct. like in any SQL statement, it has a certain order you must follow. and if you do a count on where, you basically don't give him anything to do a count on.
精彩评论