【问题标题】:Error in delete object with DbContext in c#?在 C# 中使用 DbContext 删除对象时出错?
【发布时间】:2016-05-13 02:35:49
【问题描述】:

我有这个删除方法:

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

当我单击删除按钮时,我收到此错误:

无法删除该对象,因为它在 对象状态管理器。

或者有时给我以下错误:

一个实体对象不能被多个实例引用 IEntityChangeTracker。

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

【问题讨论】:

    标签: c# entity-framework dbcontext


    【解决方案1】:

    嗯,您的第二个例外表明实体(或相关实体)附加到另一个上下文(也许您获得 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-23
      • 2015-03-02
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多