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

时间:2016-02-03 18:27:18

标签: c# entity-framework dbcontext

我有这个删除方法:

IndexIgnore *

IndexIgnore */*

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

  

无法删除该对象,因为在该对象中找不到该对象   ObjectStateManager。

或有时给我以下错误:

  

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

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

1 个答案:

答案 0 :(得分: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();
相关问题