0
When I try to delete a record from the Mapper (Model to Domain) have the following error as return from E.F:
failed because Another Entity of the same type already has the same Primary key value.
But if I do a search using the ID informed in Model and use the result to delete the record, without doing the mapping, the operation usually takes place.
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 working code:
   //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 the error occurs when I try to delete the record using return from Mapper ?
For the Entity to perform any GRUD operation the object needs to be in context why the second chunk of code works, because surely its Obtenhaporid method does _context.Entidade.Find(id); And in the first chunk of code your object is not yet mapped to the context. Ps.: I’d like to give you a more technical explanation, but unfortunately I’m not an expert on Entity.
– Netinho Santos