1

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]

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.