I have a model class Patient
:
[Key]
[Required(ErrorMessage = "")]
[MinLength(3)]
public string PatientCode { get; set; }
[Required(ErrorMessage = "")]
[MinLength(1)]
public string Name { get; set; }
[Required(ErrorMessage = "")]
[MinLength(1)]
public string Surname { get; set; }
I have a generic repository where I try to update my entity:
public async Task<bool> UpdateAsync(T entity)
{
try
{
_applicationContext.Set<T>().Update(entity);
await _applicationContext.SaveChangesAsync();
return true;
}
catch (Exception)
{
return false;
}
}
which I call from my controller:
private readonly IRepository<Patient> _patientRepository;
...
[HttpPatch("update/")]
public async Task<IActionResult> UpdateAsync([FromBody] Patient patient)
{
var result = await _patientRepository.UpdateAsync(patient);
if (result)
return Ok();
return BadRequest();
}
And when I do so, I get this error:
The instance of entity type 'Patient' cannot be tracked because another instance with the same key value for {'PatientCode'} is already being tracked
If I comment out setting the entity in my repository (comment line _applicationContext.Set<T>().Update(entity);
) everything works just fine. It means that my entity has been attached to the ChangeTracker somehow. But how is it possible in such a straight forward code?