I have the following model:
public class MyEntity
{
public Guid Id { get; set; }
public virtual ICollection<ApplicationUser> AssociatedUsers { get; set; }
public MyEntity()
{
AssociatedUsers = new HashSet<ApplicationUser>();
}
}
Notice that each entity has some associated users. In my controller, I'm trying to add an instance of MyEntity
to the database like this:
private ApplicationDbContext db = new ApplicationDbContext();
// ...
ApplicationUser currentUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().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();
However, that code throws the following error:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
I gather from that error message that CurrentUser
is still being managed by the database context which backs the ApplicationUserManager
, so I can't add it to a different context. But unlike other cases that I have found documented, I can't simply switch the context so that they share a database connection: the user object is coming from an ApplicationUserManager
. 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.