Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does multiple evaluations of an IQueryable object hit the Database multiple times?

In the Entity Framework, if I do the following:

var count = myIQueryable.Count();
var list = myIQueryable.ToList();

does that hit the Database twice? or just once?

like image 398
dmorganb Avatar asked Jun 09 '11 15:06

dmorganb


1 Answers

In order to effectively count the number of entries, the framework needs to evaluate the query, thus hitting the Database. However, because the query may have changed between the Count() and ToList(), it must evaluate again. Consider the following:

var myIQueryable = my.db<SomeModel>();  // IQueryable<SomeModel>
var countQuery = myIQueryable.Count();  // 10
MakeAdditions(myIQueryable, 10);        // adds 10 items
var list = myIQueryable.ToList();       // List<SomeModel> count=20
MakeAdditions(myIQueryable, 10);
var countList = list.Count();           // still 20, List never changed

Put another way, all calls against an IQueryable are still subject to the way it runs its queries. After capturing a query into a List, you are exclusively dealing with your in-memory List, independant of changes that occur to the IQueryable's data source.

like image 84
max Avatar answered Dec 05 '22 06:12

max