当对象与上下文分离时,如何删除EF6中的对象列表 [英] How to delete a list of objects in EF6 when the object is detached from the context
问题描述
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
到列表< MY_GROUPS>
我将如何处理删除?
有没有一种更有效的方法,那么只要做一个 foreach
并一次设置一个状态?
更新:
我已经在使用与 RemoveRange
方法类似的方法。
但是我收到一个错误:
该对象无法被删除,因为在
中找不到ObjectStateManager
我正在寻找将对象列表附加到上下文的最佳方法,以便我可以删除它们。 p>
为了能够删除记录,你需要确保你的 ObjectContext
正在跟踪他们。现在你有分离的对象,你的上下文不了解它们,所以不可能删除它们。删除它们的一种方式是像你说的一样,将
将所有对象附加到上下文中,然后删除它们。我喜欢这样做的方法是在数据库中找到适当的记录(不要抓取它们),然后删除它们:
//查找数据库中的所有组,该组中的ID位于组集合ug
var groups = context.My_Groups.Where(g => ug.Any (u => u.Id == g.Id));
context.My_Groups.RemoveRange(groups);
context.SaveChanges();
但是,请注意,即使使用 RemoveRange
,删除命令将发送到您要删除的每个项目的数据库。 RemoveRange
和删除
之间的唯一区别是,第一个只会调用 DetectChanges
一次,这可以提高性能。
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();
}
}
If this method changed from passing a single instance of MY_GROUPS
to a List<MY_GROUPS>
how would I handle the delete?
Would there be a more efficient way then just doing a foreach
and setting the state one at a time?
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.
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 way I'd prefer to do it, is to find the appropriate records in database (don't fetch them) and then 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();
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中的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!