How to delete a list of objects in EF6 when the object is detached from the context
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();
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.
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);
context.SaveChanges();
You could also use ObjectContext.ExecuteStoreCommand Method
as an another approach for this purpose.
Iterate over your collection and set Deleted
state for each
groups.ForEach(group => ctx.Entry(group).State = EntityState.Deleted);
ctx.SaveChanges();