Skip to main content
3 de 4
Formatação.
Leonel Sanches da Silva
  • 89,6mil
  • 9
  • 125
  • 233

Erro ao deletar usando Entity Framework 6 e repositório customizado

Estou usando o Entity framework para fazer o CRUD no banco de dados, mas tenho um erro ao tentar deletar algum item:

"The object cannot be deleted because it was not found in the ObjectStateManager."

Estou usando o padrão de repositório, unit of work e viewModels;

Minha classe de repositório:

public class Repositorio<TEntity> : IRepositorio<TEntity> where TEntity : class
   {
    private readonly ContextoManager _contextoManager = ServiceLocator.Current.GetInstance<IContextoManager>() as ContextoManager;
    protected readonly V1Contexto Contexto;
    protected DbSet<TEntity> DbSet;

    public Repositorio()
    {
        
        Contexto = _contextoManager.GetContexto();
        
        DbSet = Contexto.Set<TEntity>();
    }

O método excluir na classe de repositório:

 public virtual void Excluir(TEntity obj)
    {
        DbSet.Remove(obj);
    }

A classe de unit of work:

public class UnitOfWork : IUnitOfWork
{

    private readonly V1Contexto _dbContexto;
    private readonly ContextoManager _contextoManager = ServiceLocator.Current.GetInstance<IContextoManager>() as ContextoManager;
    private bool _disposed;

    public UnitOfWork()
    {
        _dbContexto = _contextoManager.GetContexto();
    }

    public void BeginTransaction()
    {
        _disposed = false;
    }

    public void SaveChanges()
    {
        _dbContexto.SaveChanges();
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _dbContexto.Dispose();
            }
        }
        _disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

Tenho uma camada de aplicação em que uso o unit of work:

public void Excluir(UsuarioViewModel usuarioViewModel)
    {
        BeginTransaction();
        var usuario = Mapper.Map<UsuarioViewModel, Usuario>(usuarioViewModel);
       _usuarioService.Excluir(usuario);
       Commit();
    }

O deletar na controller da camada de web:

    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(Guid id)
    {
        var usuarioViewModel = _usuarioAppService.ObterPorId(id);
        _usuarioAppService.Excluir(usuarioViewModel);
        return RedirectToAction("Index");
    }

    

Já tentei usar o excluir na classe de repositório assim :

public virtual void Excluir(TEntity obj)
    {
        var entry = Contexto.Entry(obj);
       
        DbSet.Attach(obj);
        
        entry.State = EntityState.Deleted;
    }

e também:

public virtual void Excluir(TEntity obj)
    {
        var entry = Contexto.Entry(obj);
       
        DbSet.Attach(obj);
        
        entry.State = EntityState.Deleted;

        DbSet.Remove(obj);

    }

Mas aí retorna o erro:

"Attaching an entity of type 'V1.Dominio.Entidades.Usuario' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate."

Para fazer os testes, eu tava removendo os dados do banco assim, que removia todos:

public virtual void Excluir(TEntity obj)
    {
    DbSet.ToList().ForEach(del => DbSet.Remove(del));

    }
Aesir
  • 1,1mil
  • 3
  • 8
  • 27