When I try to delete a record from the mapping of Mapper
(Model to Domain) I get the following error as a result of E.F
:
failed because another entity of the same type already has the same primary key value.
But if I do a search using ID
entered in Model
and use the result to delete the record, without doing the mapping, the operation normally occurs.
Excerpt from code that generates error:
//aplicação
public void Delete(MinhaModel modelo){
var entidade = Mapper.Map<Entidade>(modelo);
_meuRepository.Delete(entidade);
}
//repositório
public void Delete(T entity){
Context.Configuration.AutoDetectChangesEnabled = false;
Context.Set<T>().Attach(entity);
Context.Entry(entity).State = EntityState.Deleted;
Context.SaveChanges();
}
Excerpt from the code that works:
//aplicação
public void Delete(MinhaModel modelo){
var entidade = _meuRepositorio.ObtenhaPorId(modelo.Id);
_meuRepository.Delete(entidade);
}
//repositório
public void Delete(T entity){
Context.Configuration.AutoDetectChangesEnabled = false;
Context.Set<T>().Attach(entity);
Context.Entry(entity).State = EntityState.Deleted;
Context.SaveChanges();
}
My question is why does the error occur when I try to delete the record using the Mapper
return?