title: unable to update user via UserManager<TUser> using ef core 2.2 in asp.net core 2.2 app
body: <p>I'm trying to update the users using <code>UserManager&lt;TUser&gt;</code> but getting the following error </p>
  
  <blockquote>
    <p>The instance of entity type 'UserEntity' cannot be tracked because
    another instance with the key value '{Id}' is already being tracked.
    When attaching existing entities, ensure that only one entity instance
    with a given key value is attached.</p>
  </blockquote>
  
  <p>There are several issues in the internet with respect to above error, but none is while updating the user via <code>UserManager</code>.</p>
  
  <p>Here is my code:</p>
  
  <p><strong>Services Configuration:</strong></p>
  
  <pre class="lang-cs prettyprint-override"><code>        services.AddScoped&lt;IUserRepository, UserRepository&gt;();
          services.AddIdentity&lt;UserEntity, UserRoleEntity&gt;()
                      .AddEntityFrameworkStores&lt;GallaContext&gt;()
                      .AddDefaultTokenProviders();
  </code></pre>
  
  <p><strong>UserEntity:</strong></p>
  
  <pre class="lang-cs prettyprint-override"><code>    public class UserEntity : IdentityUser&lt;Guid&gt;
      {
          private ProfileEntity _profile;
  
          private UserEntity(ILazyLoader lazyLoader)
          {
              LazyLoader = lazyLoader;
          }
  
          private ILazyLoader LazyLoader { get; set; }
  
          public UserEntity()
          {
  
          }
  
          public string FirstName { get; set; }
          public string LastName { get; set; }
          public string Designation { get; set; }
          public string IdentityNumber { get; set; }
          public bool Active { get; set; }
          public DateTimeOffset CreatedAt { get; set; }
          public string CreatedBy { get; set; }
          public DateTimeOffset? ModifiedAt { get; set; }
          public string ModifiedBy { get; set; }
  
          public Guid ProfileId { get; set; }
          public ProfileEntity Profile { get =&gt; LazyLoader.Load(this, ref _profile); set =&gt; _profile = value; }
      }
  </code></pre>
  
  <p><strong>Razor Page Handler:</strong></p>
  
  <pre class="lang-cs prettyprint-override"><code>        public async Task&lt;IActionResult&gt; OnPutAsync(
              [FromForm] UserViewModel userViewModel,
              CancellationToken ct)
          {
              try
              {
                  await _user.InitializeAsync(userViewModel.Id, ct);
                  var user = _mapper.Map(userViewModel, _user);
  
                  var result = await user.SaveAsync(ct);
  
                  return new JsonResult(new AjaxResultHelper&lt;string&gt;(result.Succeeded)
                  {
                      Response = result.ErrorMessage ?? ResponseMessages.DataSaved
                  });
              }
              catch (Exception e)
              {
                  // Need to log the error
  
                  return new JsonResult(new AjaxResultHelper&lt;string&gt;()
                  {
                      Response = e.Message
                  });
              }
          }
  </code></pre>
  
  <p><strong>UserBusiness:</strong></p>
  
  <pre class="lang-cs prettyprint-override"><code>    public class User : CoreEntityBase
      {
          private readonly IUserRepository _userRepository;
          private readonly IMapper _mapper;
  
          public User(
              IUserRepository userRepository,
              IMapper mapper)
          {
              _userRepository = userRepository;
              _mapper = mapper;
          }
  
          public string Name =&gt; $"{FirstName} {LastName}";
          public string UserName { get; private set; }
          public string NormalizedUserName { get; private set; }
          public string Email { get; private set; }
          public string NormalizedEmail { get; private set; }
          public bool EmailConfirmed { get; private set; }
          public string PasswordHash { get; private set; }
          public string SecurityStamp { get; private set; }
          public string ConcurrencyStamp { get; private set; }
          public bool LockoutEnabled { get; private set; }
  
          [Sortable(Default = true)]
          [SearchableString]
          public string FirstName { get; set; }
  
          [Sortable]
          [SearchableString]
          public string LastName { get; set; }
  
          [Sortable]
          [SearchableString]
          public string Designation { get; set; }
  
          [Sortable]
          [SearchableString]
          public string IdentityNumber { get; set; }
  
          public Guid ProfileId { get; set; }
  
          [NestedSortable]
          [NestedSearchable]
          public Profile Profile { get; set; }
  
          public async Task InitializeAsync(
              Guid Id,
              CancellationToken ct)
          {
              if (Id == null)
              {
                  throw new ArgumentNullException($"{nameof(Id)} cannot be null");
              }
  
              var user = await _userRepository.GetUserByIdAsync(Id, ct);
              _mapper.Map(user, this);
              SecurityStamp = user.SecurityStamp;
              UserName = user.UserName;
          }
  
          public async Task&lt;User&gt; GetUserByIdAsync(
              Guid userId,
              CancellationToken ct)
          {
              var user = await _userRepository.GetUserByIdAsync(userId, ct);
  
              return _mapper.Map&lt;User&gt;(user);
          }
  
          public async Task&lt;(bool Succeeded, string ErrorMessage)&gt; SaveAsync(CancellationToken ct)
          {
              if (!Validate())
              {
                  return (false, Errors?.First());
              }
  
              //var userEntity = await _userRepository.GetUserByIdAsync(Id, ct);
              //var userEntity = _mapper.Map(this, userEntity);
              var update = await _userRepository.UpdateUserAsync(this);
  
              return update;
          }
  
          public override bool Validate()
          {
              var isValid = true;
  
              if (string.IsNullOrWhiteSpace(FirstName))
              {
                  Errors.Add("FirstName cannot be empty");
                  isValid = false;
              }
  
              if (string.IsNullOrWhiteSpace(LastName))
              {
                  Errors.Add("LastName cannot be empty");
                  isValid = false;
              }
  
              if (string.IsNullOrWhiteSpace(Designation))
              {
                  Errors.Add("Designation cannot be empty");
                  isValid = false;
              }
  
              return isValid;
          }
      }
  </code></pre>
  
  <p><strong>UserRepository:</strong></p>
  
  <pre class="lang-cs prettyprint-override"><code>    public class UserRepository : IUserRepository
      {
          private readonly UserManager&lt;UserEntity&gt; _userManager;
          private readonly IMapper _mapper;
  
          public UserRepository(
              UserManager&lt;UserEntity&gt; userManager,
              IMapper mapper)
          {
              _userManager = userManager;
              _mapper = mapper;
          }
  
          public async Task&lt;UserEntity&gt; GetUserByIdAsync(
              Guid userId,
              CancellationToken ct)
          {
              var entity = await _userManager.Users.AsNoTracking().TagWith(nameof(GetUserIdAsync))
                  .Include(u =&gt; u.Profile)
                  .SingleOrDefaultAsync(x =&gt; x.Id == userId, ct);
  
              return entity;
          }
  
          public async Task&lt;(bool Succeeded, string ErrorMessage)&gt; UpdateUserAsync(User user)
          {
              var userEntity = _mapper.Map&lt;UserEntity&gt;(user);
              var result = await _userManager.UpdateAsync(userEntity);
  
              if (result.Succeeded)
              {
                  return (true, null);
              }
  
              var firstError = result.Errors.FirstOrDefault()?.Description;
              return (false, firstError);
          }
      }
  </code></pre>
  
  <p>I'm not able to figure out where I'm wrong. I have <code>AsNoTracking()</code> set for <code>_userManager.Users</code> in <code>GetUserByIdAsync()</code> method; but still its not working and keep throwing the same error. Am I doing in a wrong way? Please assist on what needs to be corrected and where i'm  going wrong.</p>
  
  <p>Thanks in advance.</p>