As I understand it when I use LINQ extension methods (with lambda expression syntax) on IQueryable
that is in the fact instance of ObjectSet
they are t
Here's a simple explanation:
IEnumerable usersEnumerable = db.UserSet;
IQueryable usersQueryable = db.UserSet;
var users = /* one of usersEnumerable or usersQueryable */;
var age32StartsWithG = users.Where(user => user.Age == 32)
.Where(user => user.Name.StartsWith("G");
If you use usersEnumerable
, when you start enumerating over it, the two Where
s will be run in sequence; first the ObjectSet
will fetch all objects and the objects will be filtered down to those of age 32, and then these will be filtered down to those whose name starts with G.
If you use usersQueryable
, the two Where
s will return new objects which will accumulate the selection criteria, and when you start enumerating over it, it will translate all of the criteria to a query. This makes a noticeable difference.
Normally, you don't need to worry, since you'll either say var users
or ObjectSet users
when you declare your variable, which means that C# will know that you are interested in invoking the most specific method that's available on ObjectSet
, and the IQueryable
query operator methods (Where
, Select
, ...) are more specific than the IEnumerable
methods. However, if you pass around objects to methods that take IEnumerable
parameters, they might end up invoking the wrong methods.
You can also use the way this works to your advantage by using the AsEnumerable()
and AsQueryable()
methods to start using the other approach. For example, var groupedPeople = users.Where(user => user.Age > 15).AsEnumerable().GroupBy(user => user.Age);
will pull down the right users with a database query and then group the objects locally.
As other have said, it's worth repeating that nothing happens until you start enumerating the sequences (with foreach
). You should now understand why it couldn't be any other way: if all results were retrieved at once, you couldn't build up queries to be translated into a more efficient query (like an SQL query).