c# - 无法删除该对象,因为在 ObjectStateManager 中找不到它

标签 c# .net entity-framework

我有这段正常工作的代码:

db.myTable.DeleteObject(myCurrent);

我得到了这个错误:

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

相同的成分在数据库的表中。

我试过这个:

db.myTable.Attach(myCurrent);
db.myTable.DeleteObject(myCurrent);

我得到了另一个错误:

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

如何解决这个问题?

最佳答案

问题是您不能删除(或移除)分离的实体,也不能附加一个实体两次。你需要像下面这样的东西。

var entry = db.Entry(myCurrent);
if (entry.State == EntityState.Detached)
    db.myTable.Attach(myCurrent);
db.myTable.Remove(myCurrent);

关于c# - 无法删除该对象,因为在 ObjectStateManager 中找不到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15945172/

相关文章:

c# - 使用 Async/Await 时,如何在请求属性更改时更新所有请求?

c# - 使用 LockBits 生成奇怪的图像

c# - 有 2 组数据的自连接表的条件 LINQ 查询

c# - 在两个 UNC 路径之间复制文件 C# Windows.Forms 问题

c# - 使用在 C# 中使用 TripleDES 加密的 Microsoft Crypt API 在 C++ 中解密文件

c# - 如何读取我的网络服务中的 .p12 文件

c# - 将 Insert into Select 翻译成 Entity Framework

c# - 在 json 字符串中序列化 session 对象

.net - .NET Framework 4 会取代所有以前的版本吗?

entity-framework - Entity Framework -Linq到实体-多对多查询问题