【问题标题】:Error when i delete multiple rows "The object cannot be deleted because it was not found in the ObjectStateManager."删除多行时出错“无法删除该对象,因为在 ObjectStateManager 中找不到它。”
【发布时间】:2016-07-03 09:23:29
【问题描述】:

大家好,我正在使用此代码删除表中的多条记录。但它给了我一个错误。

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

我是 EF 新手,请帮我看看我的代码出了什么问题。

listOfEntities = 我要从表中删除的记录列表
U = 它是一个类型实体

using (var db = new DMContext())
{
  db.SaveChanges();
}

【问题讨论】:

    标签: c#-4.0 entity-framework-4


    【解决方案1】:

    表示该实体未附加。你可以这样试试

    using (var db = new DMContext())
    {
        db.YourTableEntity.Attach(EntityToRemove); 
        db.YourTableEntity.Remove(EntityToRemove);
        db.SaveChanges();
    }
    

    已分离的实体无法移除,需要先附加它们,然后才能移除。

    删除多条记录

    foreach (var entity in entities)
    {
        Set<T>().Attach(entity);
        Set<T>().Remove(entity);
    }
    
    SaveChanges();
    

    【讨论】:

    • 嘿 rahul 我想删除多条记录。还有一件事我想告诉你使用删除记录的通用方法。
    • 我如何附加多个实体
    • @A.Q:- 更新了我的答案。请检查。
    • 不使用循环我可以做到吗
    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    相关资源
    最近更新 更多