开发者

EF Code First and caching

I have the following pseudo code using EF Code First:

User user = GetFromCache();

Playlist playlist = new Playlist { Name = "name", User = user };开发者_开发百科

playlistRepository.Add(playlist);

unitOfWork.Commit();

The GetFromCache() method checks to see if the user is in cache and if not it uses a repository to get it from the database. If it is in cache it returns it.

When I run this code the first time all is well. When I run it the second time and it fetches the user from cache I get an exception: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

Why is that?


Entities created by a context keeps a reference to that context for lazy loading and change tracking purposes. If you are going to cache an entity you have remove the reference to that context by detaching it(As a side effect context will not be GCed until the entity has no other references).

So if you are going to cache it detach it as follows

context.Entry(user).State = EntityState.Detached;

Then inside your GetFromCache() you need to attach the entity to the current context. Otherwise EF will insert a new record for the user object.

User GetFromCache()
{
    var user = /* retrieve from cache */
    if (user != null)
    {
        context.Users.Attach(user);
    }
    else
    {
        //get user from database
    }

    return user;    
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜