title: Entity Framework - Scoping context in a web app
body: <p>I have implemented a simple repository pattern for the Entity Framework in a web app.</p>
  
  <p>I have several repositories which all subclass a base which has some common methods in</p>
  
  <p>The base looked like this</p>
  
  <pre><code>public class BaseRepository&lt;TEntity&gt; : IRepository&lt;TEntity&gt;
  {
      protected readonly RedirectsEntities Context;
  
      public BaseRepository()
      {
          Context = new RedirectsEntities();
      }
  </code></pre>
  
  <p>(RedirectsEntities is the EF datacontext, or whatever it's called)</p>
  
  <p>And I had a RuleRepository and a SiteRepository which subclassed it</p>
  
  <p>However, this caused me problems when looking up a site and using that value to save to a rule</p>
  
  <p>the error was </p>
  
  <p>"ADO.Net Entity Framework An entity object cannot be referenced by multiple instances of IEntityChangeTracker"</p>
  
  <p>Presumably because each repository has a different instance of RedirectsEntities ?</p>
  
  <p>So I found this question :
  <a href="https://stackoverflow.com/questions/694625/ado-net-entity-framework-an-entity-object-cannot-be-referenced-by-multiple-instan">ADO.Net Entity Framework An entity object cannot be referenced by multiple instances of IEntityChangeTracker</a></p>
  
  <p>which suggests moving the datacontext to a seperate class, holding it in a a static variable</p>
  
  <p>e.g.</p>
  
  <pre><code>public class DataContext
  {
      private static RedirectsEntities _dbEntities;
      public static RedirectsEntities DbEntities
      {
          get
          {
              if (_dbEntities == null)
              {
                  _dbEntities = new RedirectsEntities();
              }
              return _dbEntities;
          }
          set { _dbEntities = value; }
      }
  }
  </code></pre>
  
  <p>and then my base repository constructor would look like this :</p>
  
  <pre><code>public BaseRepository()
  {
       Context = DataContext.DbEntities;
  }
  </code></pre>
  
  <p>So this appears to have solved my problem, but I am concerned that the scope of RedirectsEntities is now incorrect. </p>
  
  <p>Can anyone comment on this?</p>