IEntityChangeTracker 的多个实例不能引用实体对象 - 更新标识模型表时



我正在尝试更新身份模型中一个名为EkipaId的自定义字段。

      public ActionResult JoinTeam(int id)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        var currentUserId = User.Identity.GetUserId();
        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        var currentUser = manager.FindById(User.Identity.GetUserId());
        currentUser.EkipaId = id;
        db.Users.Attach(currentUser);
        db.Entry(currentUser).State = System.Data.Entity.EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Ekipa", "Home");
    }

我去url/Home/JoinTeam/1,我得到了一个例外。我找到当前用户,并将EkipaId设置为URL中的Id。我得到"一个实体对象不能被IEntityChangeTracker的多个实例引用"

我读过有关分离对象的信息,但以前没有附加过。

您需要释放 DbContext,并让 UserManager 使用相同的实例。像这样:

public ActionResult JoinTeam(int id)
{
    using(ApplicationDbContext db = new ApplicationDbContext())
    {
        var currentUserId = User.Identity.GetUserId();
        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
        var currentUser = manager.FindById(User.Identity.GetUserId());
        currentUser.EkipaId = id;
        db.Users.Attach(currentUser);
        db.Entry(currentUser).State = System.Data.Entity.EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Ekipa", "Home");
    }
}

但是,不鼓励像这样创建 DbContext。看看 ASP.Net https://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection 中的依赖注入

最新更新