Keivan
Keivan

Reputation: 173

Error in delete object with DbContext in c#?

I have this delete method:

     public void Delete(DBS.BankAccount entity)
    {
        try
        {
            if (_nahidContext.Entry(entity).State == System.Data.Entity.EntityState.Detached)
            {
                _nahidContext.BankAccounts.Attach(entity);
            }
            _nahidContext.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
            //or
            //_nahidContext.BankAccounts.Remove(entity);
            _nahidContext.SaveChanges();
        }
        catch (Exception ex)
        {
            throw new ArgumentException(ex.Message);
        }
    }

when I click that delete button, I get this error:

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

or sometimes gave me the following error:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

How can I fix this and delete an object from Context DbSet?[Thanks]

Upvotes: 1

Views: 1601

Answers (1)

ocuenca
ocuenca

Reputation: 39326

Well, your second exception suggests that entity (or a related entity) is attached to another context (maybe the context where you get your BankAcount entity haven't still disposed, you should check that).

I don't know how are your getting your entities, but to avoid those exceptions you can try the following:

var entityToDelete=new BankAccount(){Id=entity.Id};//Create a new instance of BankAccount with only the Id
_nahidContext.BankAccounts.Attach(entityToDelete);
_nahidContext.BankAccounts.Remove(entityToDelete);
_nahidContext.SaveChanges();

Or just:

var entityToDelete=new BankAccount(){Id=entity.Id};//Create a new instance of BankAccount with only the Id
_nahidContext.Entry(entityToDelete).State = System.Data.Entity.EntityState.Deleted;
_nahidContext.SaveChanges();

Upvotes: 1

Related Questions