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
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.