PrivateJoker PrivateJoker -3 years ago 164
C# Question

How to delete a list of objects in EF6 when the object is detached from the context

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)


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

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

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

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

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

Answer Source

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));

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download