title: How can I reference an user object in an Entity Framework model?
body: <p>I have the following model:</p>
  
  <pre><code>public class MyEntity
  {
      public Guid Id { get; set; }
      public virtual ICollection&lt;ApplicationUser&gt; AssociatedUsers { get; set; }
  
      public MyEntity()
      {
          AssociatedUsers = new HashSet&lt;ApplicationUser&gt;();
      }
  }
  </code></pre>
  
  <p>Notice that each entity has some associated users. In my controller, I'm trying to add an instance of <code>MyEntity</code> to the database like this:</p>
  
  <pre><code>private ApplicationDbContext db = new ApplicationDbContext();
  
  // ...
  
  ApplicationUser currentUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager&lt;ApplicationUserManager&gt;().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
  
  MyEntity entityInstance = new MyEntity();
  entityInstance.Id = Guid.NewGuid();
  entityInstance.AssociatedUsers.Add(currentUser);
  db.MyEntities.Add(entityInstance);
  db.SaveChanges();
  </code></pre>
  
  <p>However, that code throws the following error:</p>
  
  <blockquote>
    <p>An entity object cannot be referenced by multiple instances of IEntityChangeTracker.</p>
  </blockquote>
  
  <p>I gather from that error message that <code>CurrentUser</code> is still being managed by the database context which backs the <code>ApplicationUserManager</code>, so I can't add it to a different context. But unlike <a href="https://stackoverflow.com/questions/10191734/entity-object-cannot-be-referenced-by-multiple-instances-of-ientitychangetracker">other cases that I have found documented</a>, I can't simply switch the context so that they share a database connection: the user object is coming from an <code>ApplicationUserManager</code>. What do I need to do to resolve this? Am I doing something fundamentally wrong? I am aware that I could use the ID instead and look up the corresponding user, but I would rather have the object accessible directly.</p>