1

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.

Community
  • 1
  • 1
Wasabi Fan
  • 1,763
  • 3
  • 22
  • 36

1 Answers1

1

Your problem is very similar to the problem found in the link you've posted. In a few words, you can't manipulate a user from different contexts. Here:

ApplicationUser currentUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

You effectively got currentUser from System.Web.HttpContext.Current.GetOwinContext(), but then you're trying to save it using db, which is an ApplicationDbContext.

Keep it on the same context, and you will have your problem solved:

var currentUser = db.Users.Find(System.Web.HttpContext.Current.User.Identity.GetUserId());

var entityInstance = new MyEntity();

entityInstance.Id = Guid.NewGuid();

entityInstance.AssociatedUsers.Add(currentUser);
db.MyEntities.Add(entityInstance);
db.SaveChanges();
Bruno Saboia
  • 332
  • 3
  • 18