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 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.
Iterate over your collection and set Deleted
state for each
groups.ForEach(group => ctx.Entry(group).State = EntityState.Deleted);
ctx.SaveChanges();
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.
I found this it worked for me. I did it in a loop before calling save changes. I wanted it to create just the delete sql command and it did.
http://www.entityframeworktutorial.net/entityframework6/delete-disconnected-entity-in-entity-framework.aspx
// disconnected entity to be deleted
var student = new Student(){ StudentId = 1 };
using (var context = new SchoolDBEntities())
{
context.Entry(student).State = System.Data.Entity.EntityState.Deleted;
context.SaveChanges();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With