'why dbcontext.savechanges() donot clear tracked entites of this dbcontext in efcore
I have an error on update entities use efcore and automapper:
Entity cannot be tracked because another instance is with the same key value
my code
var addEntityList = _wcsDbContext.ConveyorAddrInfos.Where(x => x.ConveyorAddr == "1007").AsNoTracking().ToList();
var addrInfos = _mapper.Map<List<ConveyorAddrInfoDto>>(addEntityList);
if (!addrInfos.Any())
{
_logger.LogError("error");
return;
}
// do something like this ...
foreach (var info in addrInfos)
{
info.UnitId = "Test";
}
var dest = _mapper.Map(addrInfos, addEntityList);
_wcsDbContext.ConveyorAddrInfos.UpdateRange(dest);
_wcsDbContext.SaveChanges();
//=====================update 2 times=======================
var addEntityList2 = _wcsDbContext.ConveyorAddrInfos.Where(x => x.ConveyorAddr == "1007").AsNoTracking().ToList();
var addrInfos2 = _mapper.Map<List<ConveyorAddrInfoDto>>(addEntityList2);
// do something...
foreach (var conveyorAddInfoDto in addrInfos2)
{
conveyorAddInfoDto.UnitId = string.Empty;
}
var dest2 = _mapper.Map<List<ConveyorAddrInfo>>(addrInfos2);
_wcsDbContext.ConveyorAddrInfos.UpdateRange(dest2);
_wcsDbContext.SaveChanges();
I solved by the code following
// add this after first savechanges
foreach (var entityEntry in _wcsDbContext.ChangeTracker.Entries())
{
entityEntry.State = EntityState.Detached;
}
or change the map method
var dest = _mapper.Map(addrInfos, addEntityList);
But I m confused why savechanges() donot clear tracked entites of this dbcontext in efcore
Solution 1:[1]
I think this GitHub issue sheds some light on your question: https://github.com/dotnet/efcore/issues/9118
From what I understood, the ChangeTracker
is primarily not cleared after a call to SaveChanges(Async)
because the caller might be interested in generated values from the DB (like e.g. the primary key). These properties are populated back into memory for the entities (for subsequent use).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | snake |