question

MahdiElahi-4688 avatar image
0 Votes"
MahdiElahi-4688 asked JonoStewart-6987 answered

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

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 ?








dotnet-entity-framework-core
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

what's the problem ?

The error indicates there are two different Db context instances. This error might be related to how the service scope is configured but this is only a guess since the community cannot see the relevant code.



0 Votes 0 ·

1 Answer

JonoStewart-6987 avatar image
0 Votes"
JonoStewart-6987 answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.