开发者

Why Entity Framework V1 hits DB several times with SELECT while entities are already loaded?

开发者 https://www.devze.com 2023-02-18 19:50 出处:网络
Lets say I have a Playlist class with some referenced classes. The playlist entity collection is pla开发者_运维问答ced into the data context wrapper:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号