Reputation: 14435
I'm coming from an NHibernate background to Entity Framework v4.0. When I load entities into the ObjectContext, I expect them to be cached there as long as the ObjectContext lives ('1st level cache'). So, if the same query is executed the second time, the objects are already in the ObjectContext and should not be loaded again.
Have a look at this query:
using (var context = new Model1Container()) {
//load entities from DB
var entities = context.Entity1Set.ToArray();
//entities should now be cached in the context (1st level cache)
//why does this call not use the cached items?
entities = context.Entity1Set.ToArray();
}
In SQL Server Profiler, I can clearly see that both ToArray() calls trigger a database query. Why does the second query need a DB roundtrip, as opposed to the NHibernate behavior?
Thanks!
Upvotes: 1
Views: 460
Reputation: 689
EF 4.0 do not support any form of cache, neither first nor second level cache as NHibernate do.
One feature that resembles to NHibernate first-level cache was implemented in EF 4.1.
HTH
Riana
Upvotes: 1
Reputation: 15143
Good question. I've never used NHibernate, but I have been using Entity Framework for the last year or so.
In some ways, the behavior you described makes sense to me. What if the data in the database changes between calls? For example, Entity Framework would have to requery the database to check if any new rows have been added to the database table.
However, executing a LINQ query on the results would not require another roundtrip to the database because Entity Framework would be fetching the existing entities out of the ObjectContext.
var newEntities = entities.Where(x=>x.id==1).ToList();
var newEntities2 = entities.Where(x=>x.id==1).ToList();
Upvotes: 2