title: Why is the unit of work repository i created causing a System.InvalidOperationException when inserting a new item
body: <p>After writing many repositories and interfaces for my data access i understood that ive been rewriting many codes over and over so i sought to understand the generic repository pattern and the unit of work. I followed the tutorial <a href="http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application" rel="nofollow">here</a>.
  After implementing the example and incorporating the needed part to my project. I faced the problem of </p>
  
  <pre><code>An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
  Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
  </code></pre>
  
  <p>From my research i was made to understand that i could be using two database contexts hence the error. I have this GenericRepository class and the Unit of work class where i register all my repository below</p>
  
  <pre><code>public class GenericRepository&lt;TEntity&gt; where TEntity : class
  {
      internal ApplicationDbContext context;
      internal DbSet&lt;TEntity&gt; dbSet;
      public GenericRepository(ApplicationDbContext context)
      {
          this.context = context;
          this.dbSet = context.Set&lt;TEntity&gt;();
      }
      public virtual IEnumerable&lt;TEntity&gt; Get(
          Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null,
          Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null,
          string includeProperties = "")
      {
          IQueryable&lt;TEntity&gt; query = dbSet;
          if (filter != null)
          {
              query = query.Where(filter);
          }
          foreach (var includeProperty in includeProperties.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries))
          {
              query = query.Include(includeProperty);
          }
          if (orderBy != null)
          {
              return orderBy(query).ToList();
          }
          else
          {
              return query.ToList();
          }
      }
      public virtual TEntity GetByID(object id)
      {
          return dbSet.Find(id);
      }
      public virtual void Insert(TEntity entity)
      {
          if (dbSet != null) dbSet.Add(entity);
      }
      public virtual void Delete(object id)
      {
          TEntity entityToDelete = dbSet.Find(id);
          Delete(entityToDelete);
      }
      public virtual void Delete(TEntity entityToDelete)
      {
          if (context.Entry(entityToDelete).State == EntityState.Detached)
          {
              dbSet.Attach(entityToDelete);
          }
          dbSet.Remove(entityToDelete);
      }
      public virtual void Update(TEntity entityToUpdate)
      {
          dbSet.Attach(entityToUpdate);
          context.Entry(entityToUpdate).State = EntityState.Modified;
      }
  }
  </code></pre>
  
  <p>Here is the unit of work class</p>
  
  <pre><code>public class UnitOfWork : IDisposable
  {
      private ApplicationDbContext context = new ApplicationDbContext();
      private GenericRepository&lt;Transactions&gt; transactionRepository;
      private GenericRepository&lt;PendingReason&gt; penReasonRepository;
      private GenericRepository&lt;DeclineReason&gt; decReasonRepository;
      private GenericRepository&lt;LoanStatus&gt; loanStatusRepository;
      private GenericRepository&lt;SalesAgent&gt; salesAgentRepository;
     public GenericRepository&lt;Transactions&gt; TransactionRepository
      {
          get
          {
              if (this.transactionRepository == null)
              {
                  this.transactionRepository = new GenericRepository&lt;Transactions&gt;(context);
              }
              return transactionRepository;
          }
      }
      public GenericRepository&lt;PendingReason&gt; PenReasonRepository
      {
          get
          {
              if (this.penReasonRepository == null)
              {
                  this.penReasonRepository = new GenericRepository&lt;PendingReason&gt;(context);
              }
              return penReasonRepository ;
          }
      }
      public GenericRepository&lt;DeclineReason&gt; DecReasonRepository
      {
          get
          {
              if (this.decReasonRepository == null)
              {
                  this.decReasonRepository = new GenericRepository&lt;DeclineReason&gt;(context);
              }
              return decReasonRepository;
          }
      }
      public GenericRepository&lt;LoanStatus&gt; LoanStatusRepository
      {
          get
          {
              if (this.loanStatusRepository == null)
              {
                  this.loanStatusRepository = new GenericRepository&lt;LoanStatus&gt;(context);
              }
              return loanStatusRepository;
          }
      }
      public GenericRepository&lt;SalesAgent&gt; SalesAgentRepository
      {
          get
          {
              if (this.salesAgentRepository == null)
              {
                  this.salesAgentRepository = new GenericRepository&lt;SalesAgent&gt;(context);
              }
              return salesAgentRepository;
          }
      }
      public void Save()
      {
          context.SaveChanges();
      }
      private bool disposed = false;
      protected virtual void Dispose(bool disposing)
      {
          if (!this.disposed)
          {
              if (disposing)
              {
                  context.Dispose();
              }
          }
          this.disposed = true;
      }
      public void Dispose()
      {
          Dispose(true);
          GC.SuppressFinalize(this);
      }
  }
  </code></pre>
  
  <p>In my the create action of my  controller i have a point where i use the usermanager object to get the id of the current user. In that point there is a reference to the ApplicationDbContext which i think is causing the problem. However i may be wrong. Below is my controller action</p>
  
  <pre><code>    [HttpPost]
      public ActionResult Create(Transactions transactions)
      {
          using (var unit = new UnitOfWork())
          {
              if (ModelState.IsValid)
              {
                  MapTransactions(new CreateTrnVM(), transactions);
                  unit.TransactionRepository.Insert(transactions);
                  unit.Save();
                  return RedirectToAction("Index");
              }
              ViewBag.DeclineReasonId = new SelectList(unit.DecReasonRepository.Get(), "DeclineReasonId", "DecReason");
              ViewBag.PendingReasonsId = new SelectList(unit.PenReasonRepository.Get(), "PendingReasonId", "PenReason");
              ViewBag.StatusId = new SelectList(unit.LoanStatusRepository.Get(), "StatusId", "Status");
              return View(new CreateTrnVM());
          }
  </code></pre>
  
  <p>This is the MapTransactions Method.</p>
  
  <pre><code>public void MapTransactions(CreateTrnVM model, Transactions source)
      {
          source.TrnDate = DateTime.Now;
          ApplicationUser currentUser;
          using (var manager = new UserManager&lt;ApplicationUser&gt;(new UserStore&lt;ApplicationUser&gt;(new ApplicationDbContext())))
          {
              currentUser = manager.FindById(User.Identity.GetUserId());
          }
          source.Agent = currentUser.SalesAgent;
      }
  </code></pre>
  
  <p>When trying to create a Transaction, This error keeps coming out </p>
  
  <pre><code>System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
      Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker. 
  </code></pre>
  
  <p>A further research led me to this statement on this link. </p>
  
  <blockquote>
    <p>In a real application you’ll have to decide if you want to mingle your
    data context with IdentityDbContext. One issue to be aware of is that
    the UserStore class does not play well when using the unit of work
    design pattern. Specifically, the UserStore invokes SaveChanges in
    nearly every method call by default, which makes it easy to
    prematurely commit a unit of work. To change this behavior, change the
    AutoSaveChanges flag on the UserStore.</p>
  </blockquote>
  
  <pre><code>var store = new UserStore&lt;ApplicationUser&gt;(new ApplicationDbContext());
  store.AutoSaveChanges = false;
  </code></pre>
  
  <p>This still didnt work. or maybe something else is the problem.</p>