错误帐户控制器中的IEntityChangeTracker的多个实例无法引用实体对象

时间:2019-08-22 12:32:27

标签: c# asp.net-mvc code-first dbcontext asp.net-mvc-5.2

我需要为特定用户更改“身份用户”中的一个值,但是当我更改阶段时,会出现此错误(IEntityChangeTracker的多个实例无法引用一个实体对象)?

解锁帐户视图模型,如以下代码所示:

    public class AccountLockoutViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }
    }

这是AccountController中的ActionResult Unlock Account的代码:

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult UnlockAccount(AccountLockoutViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var user =  UserManager.FindByName(model.Email);
            if (user == null)
            {
                // Don't reveal that the user does not exist
                return RedirectToAction("UnlockAccountConfirmation", "Account");
            }
            else
            {

                user.LockoutEnabled = false;
                //Identitydb.Users.Attach(user);   <--- I tried this solution also but it is not work
                Identitydb.Entry(user).State = EntityState.Modified; //The error raised here
                Identitydb.SaveChanges();

                return RedirectToAction("UnlockAccountConfirmation", "Account");
            }
            return View();
        }

引发的错误,如以下图片链接所示: Error raised location

我读了很多文章,在这种情况下工作太多,但是直到现在我还没有找到解决方法。

我访问了一些链接:
1- Entity object cannot be referenced by multiple instances of IEntityChangeTracker in a generic repository
2- An entity object cannot be referenced by multiple instances of IEntityChangeTracker
3- An entity object cannot be referenced by multiple instances of IEntityChangeTracker" Exception Occur when adding value to the table using Entity Framework

如果您了解问题,请写出解决方案,谢谢。

1 个答案:

答案 0 :(得分:0)

UserManager.FindByName的实现方式。曾经在选择用户时尝试过使用.AsNoTracking()吗? 像这样的东西:context.Users.AsNoTracking().FirstOrDefault(....) AsNoTracking()必须使用。

相关问题