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

c# entity-framework entity-framework-6


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 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.

3/8/2016 2:02:36 PM

Accepted Answer

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

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.

11/23/2017 2:42:28 PM

Popular Answer

You can use RemoveRange:

context.MY_GROUPS.RemoveRange(context.MY_GROUPS.Where(x => x.columnName== "Foo"));

You can also use ForEach like this:

context.MY_GROUPS.Where(x => x.columnName == "Foo").ToList().ForEach(context.DeleteObject);

You could also use ObjectContext.ExecuteStoreCommand Method as an another approach for this purpose.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow