Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences when using IEnumerable and IQueryable as a type of ObjectSet

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 translated into LINQ to SQL queries. What I mean is that command

IQueryable<User> users = db.UserSet;
var users32YearsOld = users.Where(user => user.Age == 32);

is exactly the same as

IQueryable<User> users = db.UserSet;   
var users32YearsOld = from user in users where user.Age == 32 select user;

So non of them hits database until they users32YearsOld are enumerated in for cycle or such. (Hope I understand this correctly).

But what is going to happen if I don't mask that ObjectSet as IQueryable but as IEnumerable ? So if the type of it is IEnumerable ?

IEnumerable<User> users = db.UserSet;
var users32YearsOld = users.Where(user => user.Age == 32);

Is it going to hit the database immediately (if so then when ? Right on the first line or on the second) ? Or is it going to behave as the previous command that is will not hit database until users32YearsOld is enumerated ? Will there be any difference if I use following instead ?

IEnumerable<User> users = db.UserSet;
var users32YearsOld = from user in users where user.Age == 32 select user;

Thank you

like image 905
Rasto Avatar asked Mar 24 '11 08:03

Rasto


1 Answers

Undeleting my answer because I just tested it and it works exactly as I described:

None of mentioned queries will hit the database because there was no enumeration. The difference between IQueryable query and IEnumerable query is that in the case of IQueryable the filtering will be executed on the database server whereas in the case of IEnumerable all objects will be loaded from the database to a memory and the filtering will be done in .NET code (linq-to-objects). As you can imagine that is usually performance killer.

I wrote simple test in my project:

[TestMethod]
public void Test()
{
    // ObjectQuery<Department> converted ot IEnumerable<Department>
    IEnumerable<Department> departmetns = CreateUnitOfWork().GetRepository<Department>().GetQuery();
    // No query execution here - Enumerable has also deffered exection
    var query = departmetns.Where(d => d.Id == 1); 
    // Queries ALL DEPARTMENTS here and executes First on the retrieved result set
    var result = departmetns.First(); 
}
like image 188
Ladislav Mrnka Avatar answered Oct 02 '22 13:10

Ladislav Mrnka