title: How to detach entities from EF Code First contexts
body: <p>This seems a lot harder than it should be.</p>
  
  <p>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.</p>
  
  <p>Since the list of events isn't likely to change much, I'm caching it into a global list in the Application_Start method:</p>
  
  <pre><code>        var repo = new RaceEventRepository();
              EventRaces =
                  repo.All.Where(r =&gt; r.RaceName.Contains(eventName)).Select(r =&gt; r).ToList();
  </code></pre>
  
  <p>where RaceEventRepository is a repository class constructed by MvcScaffolding, and does a </p>
  
  <pre><code>EventContext context = new EventContext();
  </code></pre>
  
  <p>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.</p>
  
  <p>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."</p>
  
  <p>According to several blog posts and SO answers, I need to Detach the cached entities from the context as in <a href="http://www.code-magazine.com/article.aspx?quickid=0907071&amp;page=4" rel="nofollow">Listing 1 of this post</a>.</p>
  
  <p>My problem is that, using ObjectBrowser, 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.</p>
  
  <p>Clearly, I'm missing something.  Can somebody point me in the right direction?  </p>