Error In Update Record (The instance of entity type 'x' cannot be tracked)

Mahdi Elahi 26 Reputation points
2022-02-20T11:47:53.197+00:00

I have this error when update record in RoleRepository.cs.
i use AsNoTracking but show error again

The instance of entity type 'ApplicationRole' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

RoleController.cs

  public async Task<IActionResult> Edit(string id)
        {
            if (id == null)
            {
                return NotFound();
            }
            if (!await _roleService.ExsistIdAsync(id))
            {
                return NotFound();
            }
            return PartialView(await _roleService.GetAsync(id));
        }

public async Task<IActionResult> Edit(RoleViewModel role)
        {                  
                if (await _roleService.ExsistNameAsync(role))
                {
                   //show message duplicate name
                }
                await _roleService.UpdateAsync(role);
                return Json(new { res = true, model = role });

        }

RoleService.cs

public async Task<IdentityResult> UpdateAsync(RoleViewModel role)
    {
        var mapped = ObjectMapper.Mapper.Map<ApplicationRole>(role);
        return await _roleRepository.UpdateAsync(mapped);
    }

RoleRepository.cs

  public async Task<IdentityResult> UpdateAsync(ApplicationRole role)
        {
            return await _roleManager.UpdateAsync(role);
        }
    public async Task<ApplicationRole> GetAsync(string Id)
        {
            return await _db.Roles.Where(x=>x.Id==Id).AsNoTracking().FirstOrDefaultAsync();
        }

what's the problem ?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
694 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Jono Stewart 21 Reputation points
    2022-07-29T14:50:20.55+00:00

    Encountered this myself today.

    Any entities queried using AsNoTracking can not be used somewhere in the Entity tree of any that I do add/update.

    i.e. where you are querying for Role AsNoTracking, you can not then update it, or any dependent entity queried with AsNoTracking.

    4 people found this answer helpful.

  2. Vinod Mathew 0 Reputation points
    2023-03-02T15:01:08.92+00:00
    0 comments No comments

  3. Vinod Mathew 0 Reputation points
    2023-03-02T15:02:44.2866667+00:00

    Please consider making your repository class scoped if it is a singleton

    0 comments No comments