When I want to update an entity, I face the following error:
Message = "The instance of entity type 'Vehicle' 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. Conside...
I have added the database as addScope. I think the problem is during Mapping because when I manually fill the Entity fields with the sent request, it works without any problem. My question is how to map the properties? Each of my Entity has a lot of properties and it is difficult to manually enter all these working values.
Update method:
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult> UpdateVehicle(UpdateVehicleCommand command)
{
if (string.IsNullOrEmpty(command.Id))
{
return BadRequest();
}
try
{
var result = await Mediator.Send(command);
return Ok(result);
}
catch (Exception e)
{
_logger.LogError("Can not Update Vehicle because : {e}", e.Message);
return BadRequest();
}
}
in UpdateVehicleCommand :
public async Task<Unit> Handle(UpdateVehicleCommand request, CancellationToken cancellationToken)
{
var entity = await _context.Vehicles
.FindAsync(new object[] { request.Id }, cancellationToken);
if (entity == null)
{
throw new NotFoundException(nameof(Vehicle), request.Id);
}
// *********** Mapping ****************
// ****The problem is in the following line****
_context.Vehicles.Update(_mapper.Map<Domain.Entities.Vehicle.Vehicle>(request));
***********Import in manual mode************
//entity.ImageDocument = request.ImageDocument;
//entity.ImageFrontCard = request.ImageFrontCard;
//entity.ImageBackCard = request.ImageBackCard;
.....
.....
.....
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
Profile settings for automapper are also added correctly