Wednesday, October 16, 2013

Entity Framework Extensions to execute scalar queries (.First(), .Any(), .Count(), ...)

If you have used LINQ to SQL, Entity Framework you might noticed that when you use queryable extensions returning set of objects (like .Select(), .Where(), .Join(), Group...) you get defered-executable queries that will be converted to SQL end executed during first demand. You can combine those queries, join them together, and it eventually will be still one SQL request. However you don't get the same when you work with functions returning not Enumerable, but actual value (like .First(), .Any(), .Max(), ...). So thanks to people from Stackoverflow, here are extensions for DbContext and DbQuery (Entity Framework 5), that will allow you to execute those operations still getting back Queryable results:
Here are examples, how to use this code:
SQL generated for each statement is the same: