locked
Having problem with updating IdentityUser - The instance of entity type 'User' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked RRS feed

  • Question

  • User756251838 posted

    Hello.

    I am using ASP.NET Core 3.1.7 with Identity 3.1.7 and in my current project I didn't use any DTO for creating / updating  User.

    and I use the main entity User that derived from IdentityUser.. these codes are for updating the user but i have problem with ChangeTracker.

    this is my User Entity.

     public class User : IdentityUser<int>
        {
            public int DepartmentId { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string NationalCode { get; set; }
            public string Address { get; set; }
            public string IPAddress { get; set; }
            public CorporateTitle CorporateTitle { get; set; }
            public string PhotoPath { get; set; }
    
            [NotMapped]
            public IFormFile Photo { get; set; }
    
            [NotMapped]
            public string[] Roles { get; set; }
    
    
            public DateTimeOffset DateCreated { get; set; }
            public DateTimeOffset DateModified { get; set; }
    
            [ForeignKey(nameof(DepartmentId))]
            public Department Department { get; set; }
    
            public ICollection<UserRole> UserRoles { get; set; }
    
    
        }

    this block of code is for getting the user and then showing it in view. and its ok and working properly.

     public async Task<IActionResult> EditUser(string id)
            {
                if (!string.IsNullOrEmpty(id))
                {
                    var usertoEdit =  await _userRepository.FindByIdAsync(id);
                    var userRoles = await _userRepository.GetAllUserRolesAsync(usertoEdit);
                    //
                    usertoEdit.Roles = userRoles.ToArray();
                    //
                    if (usertoEdit == null)
                    {
                        ViewBag.ErrorMessage = $"some error..";
                        return View("NotFound");
                    }
    
                    SelectLists();
                    return View(usertoEdit);
                }
                else
                {
                    ViewBag.ErrorMessage = $"some error.";
                    return View("NotFound");
                }
            }

      [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> EditUser(User user)
            {
                if (ModelState.IsValid)
                {
                   
                
                    var editUserResult = await _userRepository.EditUserAsync(user); // here i have problem and after that showing error.
    
                    if (editUserResult.Succeeded)
                    {
                        await _userRepository.RemoveAllUserRolesAsync(user);
                        if (user.Roles != null)
                        {
                            await _userRepository.AddRolesToUserAsync(user, user.Roles);
                        }
    
                        TempData["UserEditedSuccessfully"] = $"some error.";
                        return RedirectToAction(nameof(Index));
                    }
    
                    foreach (var error in editUserResult.Errors)
                    {
                        ModelState.AddModelError(error.Code, error.Description);
                    }
    
                    SelectLists();
                    return View(user);
    
                }
                else
                {
                    SelectLists();
                    return View(user);
                }
            }

    please help me to solve this problem without use any DTO or ViewModel thanks.

    Friday, August 21, 2020 5:48 PM

Answers

  • User756251838 posted

    thanks, I solved the problem.

    the problem is that when user sent to post action its not attach to ChangeTracker and ChangeTracker Cant specifty that.

    _db.Attach(user);

    solved with this line of code.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 21, 2020 7:08 PM

All replies

  • User475983607 posted

    The error means two different DbContext instances were created.  We see this error a lot when the repository pattern is implemented incorrectly.  The best advice is to drop the repository or generic repository unless you know what you're doing.

    Friday, August 21, 2020 6:09 PM
  • User756251838 posted

    I just use a normal repository its not generic. and  I test this scenario without any repository, just injected UserManager in controller.. and have the same issue.

    ( and i just have UserManager in my repository class)

    i think the problem is in the post action.

    Friday, August 21, 2020 6:16 PM
  • User475983607 posted

    i think the problem is in the post action.

    Again, this is a very common error that happens when the request has more than one DbContext and the logic uses both.  There can also be a missing await on an async method but that usually causes a threading error.   Also make sure the Dbcontext DI configuration is scope and not transient. 

    Friday, August 21, 2020 6:40 PM
  • User756251838 posted

    thanks, I solved the problem.

    the problem is that when user sent to post action its not attach to ChangeTracker and ChangeTracker Cant specifty that.

    _db.Attach(user);

    solved with this line of code.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 21, 2020 7:08 PM