Does multiple evaluations of an IQueryable object hit the Database multiple times?
In the Entity Framework, i开发者_Go百科f I do the following:
var count = myIQueryable.Count();
var list = myIQueryable.ToList();
does that hit the Database twice? or just once?
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.
Yes, it does hit the database twice, as both Count
and ToList
are eagerly evaluated. If you just want to access it once, do the following:
var list = myIQueryable.ToList();
var count = list.Count;
精彩评论