Update entity with Auto Mapper

When we try to update the existing date with Entity Framework, you might to following steps.

//
var modelMappedFromViewModel = _mapper.Map<EntityModel>(viewModel);

var modelFromDb = await _dbContext.EntityModels
                        .FirstOrDefaultAsync(c => c.Id== viewModel.Id);

if (entityConfig == null)
	throw new Exception("Data Not Found");

modelMappedFromViewModel.Id= modelFromDb.Id;

_dbContext.DealerConfigs.Attach(modelMappedFromViewModel);
_dbContext.Entry(modelMappedFromViewModel).State = EntityState.Modified;

await _dbContext.SaveChangesAsync();

In above case, application will get following error.

The instance of entity type '{Model}' cannot be tracked because another instance with the key value '{Id: 2589}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

To resolve this error, this .AsNoTracking() at finding object.

//
var modelMappedFromViewModel = _mapper.Map<EntityModel>(viewModel);

var modelFromDb = await _dbContext.EntityModels
                        .AsNoTracking()
                        .FirstOrDefaultAsync(c => c.Id== viewModel.Id);

if (entityConfig == null)
	throw new Exception("Data Not Found");

modelMappedFromViewModel.Id= modelFromDb.Id;

_dbContext.DealerConfigs.Attach(modelMappedFromViewModel);
_dbContext.Entry(modelMappedFromViewModel).State = EntityState.Modified;

await _dbContext.SaveChangesAsync();

Leave a Reply