In LINQ-to-Entities you can query entities by doing:
var students = SchoolContext.Students.Where(s => s.Name == "Foo" && s.Id == 1);
I know that behind the scenes it will be translated to SQL to something similar to:
SELECT * FROM Students WHERE Name = 'Foo' AND Id = 1
However is there a difference (with respect to performance) if I write:
var students = SchoolContext.Students .Where(s => s.Name == "Foo") .Where(s => s.Id == 1);
Will it be translated to the same SQL query? From my understanding .Where()
will return IEnumerable<T>
so the second .Where()
will filter the entities in-memory instead of translating the IQueryable<T>
to SQL, is that correct?
Advertisement
Answer
The first .Where()
clause will still return an IQueryable<T>
. As long as you are operating on an IQueryable<T>
it will continue building up the SQL query and execute it when the collection needs to be brought into memory (eg: as @anaximander stated when used in a foreach
loop or ToList()
operation.
Therefore:
SchoolContext.Students.Where(s => s.Name == "Foo").Where(s => s.Id == 1);
Still translates into:
SELECT * FROM Students WHERE Name = 'Foo' AND Id = 1
Whilst the below 2 statements will translate into the same query:
SchoolContext.Students.Where(s => s.Name == "Foo").Where(s => s.Id == 1); SchoolContext.Students.Where(s => s.Name == "Foo" && s.Id == 1);