当对象从上下文中分离时如何删除 EF6 中的对象列表

How to delete a list of objects in EF6 when the object is detached from the context(当对象从上下文中分离时如何删除 EF6 中的对象列表)

本文介绍了当对象从上下文中分离时如何删除 EF6 中的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我可以像这样删除 EF6 中的单个项目:

OK I can delete a single item in EF6 like this:

public void DeleteUserGroup(MY_GROUPS ug)
{
    using (var context = new MYConn())
    {
        var entry = context.Entry(ug);
        if (entry.State == EntityState.Detached)
        {
            context.MY_GROUPS.Attach(ug);
        }

        context.MY_GROUPS.Remove(ug);
        context.SaveChanges();
    }
}

如果此方法从将 MY_GROUPS 的单个实例传递到 List 我将如何处理删除?

If this method changed from passing a single instance of MY_GROUPS to a List<MY_GROUPS> how would I handle the delete?

是否有比只执行 foreach 并一次设置一个状态更有效的方法?

Would there be a more efficient way then just doing a foreach and setting the state one at a time?

更新:我已经在使用与上述类似的方法,即 RemoveRange 方法.但是我收到一个错误:

UPDATE: I am already using a similar method as above utilizing the RemoveRange method. However I am getting an error:

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

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

我正在寻找将对象列表附加到上下文以便删除它们的最佳方法.

I'm looking for the best way to attach a list of objects to the context so that I can delete them.

推荐答案

为了能够删除记录,您需要确保您的 ObjectContext 正在跟踪它们.现在你已经分离了对象,你的上下文不知道它们,所以不可能删除它们.删除它们的一种方法是像您说的那样,将所有对象 Attach 到上下文,然后删除它们.另一种方法是从数据库中获取记录,以便您可以删除它们:

To be able to remove records, you need to make sure your ObjectContext is tracking them. Right now you have detached objects, and your context has no knowledge of them so it's impossible to delete them. One way to remove them is to do like you say, Attach all your objects to the context, then delete them. The other way is to fetch the records from the database so you can remove them:

//Find all groups in database with an Id that is in your group collection 'ug'
var groups = context.My_Groups.Where(g => ug.Any(u => u.Id == g.Id));
context.My_Groups.RemoveRange(groups);
context.SaveChanges();

但是,请注意,即使在使用 RemoveRange 时,删除命令也会发送到数据库 per 您要删除的项目.RemoveRangeRemove 唯一的区别就是第一个只会调用一次DetectChanges,确实可以提升性能.

However, note that even while using RemoveRange, a delete command will be send to the database per item you want to remove. The only difference between RemoveRange and Remove is that the first will only call DetectChanges once, which can really improve performance.

这篇关于当对象从上下文中分离时如何删除 EF6 中的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:当对象从上下文中分离时如何删除 EF6 中的对象列表

基础教程推荐