Error deleting registration with Entity Framework when doing entity mapping

0

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?

    
asked by anonymous 04.07.2018 / 20:29

1 answer

0
  

My question is why does the error occur when I try to delete the record using the Mapper return?

When you load the database objects with the Entity Framework, these objects are cached by reference. So when you try to give attach in the entity, the EF will first look in that cache, when you give a mapping, the reference of the object is different (even the ID being the same, so EF believes you are trying to save another object with an ID that already exists), and when you give findById it also looks first in the cache (so it works, the object reference is the same).

You can remove the entity from the database by replacing the

Context.Set<T>().Attach(entity);
Context.Entry(entity).State = EntityState.Deleted;

by:

Context.Set<T>().Remove(entity);

Or, if you do not want to cache entities, use the AsNoTracking () method.

    
05.07.2018 / 18:06