I'm using Linq to Entities in my program, and i have the following two simple queries:
var result = dbContext.Customers.Where(c => c.Name == "Mostafa").ToList();
var result2 = dbContext.Customers.Where(c => c.Name == "Mostafa").AsEnumerable().ToList();
when i run the SQL Profiler, i found that the generated SQL Query is the same for both of the queries ! the questions is why in the second query, although i'm using asEnumerable, executes the filtering on the server side ?
Update: The filtering was applied on memory instead of the server when changing the second query to be like this:
var result2 = dbContext.Customers.AsEnumerable().Where(c => c.Name == "Mostafa").ToList();
Thanks to @Willem Van Onsem
AsEnumerable()
makes the remainder of the query execute locally. Anything earlier than the AsEnumerable()
is still part of the IQueryable
execution flow. For example, think about this (imagining an Age
property):
var result = dbContext.Customers
.Where(c => c.Name == "Mostafa")
.Where(c => c.Age == 18)
.ToList();
That would result in SQL which filtered by name and age. Compare that with this:
var result = dbContext.Customers
.Where(c => c.Name == "Mostafa")
.AsEnumerable()
.Where(c => c.Age == 18)
.ToList();
That would filter by name in the SQL, but it would filter by age locally (in memory).
See more on this question at Stackoverflow