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 = _context.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With