How to detach entities from EF Code First contexts
This seems a lot harder than it should be.
I'm writing an event registration site using MVC3, SQL Compact Edition, and Entity Frameworks Code First, and making use of Steven Sanderson's Mvc Scaffolding NuGet package.
Since the list of events isn't likely to change much, I'm caching it into a global list in the Application_Start method:
var repo = new RaceEventRepository();
EventRaces =
repo.All.Where(r => r.RaceName.Contains(eventName)).Select(r => r).ToList();
where RaceEventRepository is a repository class constructed by MvcScaffolding, and does a
EventContext context = new EventContext();
which is then used through out the repository, and (I assume) disposed of when the Repository is disposed of. and EventRaces is a globally available List.
My problem is that when I then create a registrant record with a foreign key back to the RaceEvent that is stored in EventRaces , I'm getting an error "An entity object cannot be referenced by multiple instances of IEntityChangeTracker."
According to several blog posts and SO answers, I need to Detach the cached entities from the context as in Listing 1 of this post.
My problem is that, using ObjectBrowse开发者_运维知识库r, I can't find anything with a Detach method. context in the Repository doesn't have one. The individual DbSets in the context don't have one (although they have an Attach() method). System.Data.Object.ObjectSet has one, but I can't find a mapping between a DbSet and an ObjectSet.
Clearly, I'm missing something. Can somebody point me in the right direction?
You can either use the AsNoTracking
extension method to query your list without attaching the objects to the context ...
var repo = new RaceEventRepository();
EventRaces = repo.All.AsNoTracking()
.Where(r => r.RaceName.Contains(eventName))
.ToList();
... or you can detach single entities from the context by settings their state to Detached
:
context.Entry(raceEvent).State = EntityState.Detached;
精彩评论