Does Linz retrieve all records first if I make a graph?

Suppose I have a table called Population that stores some demographic data. In T-SQL, to get the number of people over 50, I can 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); 

To really get an account, I need to do one 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 scripts above?

+7
source share
3 answers

Linq does not retrieve all records in the first place. He defers the execution of the request until the last moment. This allows you to optimize the request.

http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx

I found that order is important sometimes. Hope this helps.

Bean

+2
source

In all cases, Count() will NOT perform in-memory calculations based on the records returned from the database, but will actually modify the generated SQL to include the COUNT statement. The simplest version of your generated TSQL query would look something like this:

 SELECT COUNT(1) FROM [dbo].[Population] AS [Extent1] WHERE [Extent1].[Age] > 50 

When calling Count() query is executed immediately. All of your queries seem to be correct, so check your database, provider, and context to make sure the query is running correctly.

+1
source

Correctly. as with any SQL statement, it has a specific order that you must follow. and if you count on where you basically give him nothing to count on.

-2
source

All Articles