Error when deleting record with Entity Framework when mapping entity

Asked

Viewed 164 times

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.

1 answer

0

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

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

You can remove the entity from the database by replacing the code

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

for:

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

Or, if you don’t want to cache entities, use the Asnotracking method().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.