在 C# 中使用 DbContext 删除对象时出错?

Error in delete object with DbContext in c#?

我有这个删除方法:

     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);
        }
    }

当我点击那个删除按钮时,我得到这个错误:

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

或者有时会出现以下错误:

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

如何解决此问题并从 Context DbSet 中删除对象?[谢谢]

好吧,您的第二个异常表明实体(或相关实体)附加到另一个上下文(也许您获得 BankAcount 实体的上下文尚未处理,您应该检查一下)。

我不知道你是如何获得实体的,但要避免这些异常,你可以尝试以下操作:

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();

或者只是:

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();