Why Entity Framework V1 hits DB several times with SELECT while entities are already loaded?
Lets say I have a Playlist class with some referenced classes. The playlist entity collection is pla开发者_运维问答ced into the data context wrapper:
public new IQueryable<Playlist> Playlist
{
get
{
return base.Playlist
.Include("PlaylistStep")
.Include("PlaylistStepAttachment");
}
}
The context is shared between application components at per-web-request basis. The first call for playlists entities looks like:
var playlist =
dataContext
.Playlist
.Where(x => x.OwnerUserId == ownerId)
.OrderBy(x => x.Name)
.Skip((page - 1) * count)
.Take(count)
.ToList();
This generates appropriate SQL statement and loads some playlists into the context, as far as I understand. Then in the same web request I have several calls:
var playlist = dataContext
.Playlist
.Where(x => x.PlaylistId == id)
.FirstOrDefault();
where playlist ids are the same as were got during the first request. What surprises me is that subsequent calls generate SQL statements too, though those entities were already loaded into the context. I believe entities that are already in the context should be returned, not retrieved by the DB again.
Could please someone tell me where I'm mistaken, or this behavior is normal for EF?
this seems to explain the issue: http://connect.microsoft.com/VisualStudio/feedback/details/511785/implement-caching-in-entity-framework
Currently the EF only supports a first level cache out of the box. First level caching is basically just identity resolution of entities in query results. All queries still hit the server and bring back full entity results.
The behavior you're seeing is normal, because enumerating ObjectQuery<T>
always does a DB query.
You can query locally-loaded objects by looking into the ObjectContext.ObjectStateManager
. This works fine, though the syntax is less intuitive.
EF 4.1 introduces the new DbSet<T>.Local
property, which makes this easier.
精彩评论