Reputation: 733
I've got a list of objects that I want to delete from the database. Is there a better way to do it than by using:
foreach (Entity e in entities)
{
context.Entities.remove(e);
}
Apparently this will make a delete query at each time to the DB, which is really time consuming.
Finally I decided to do it in other way, but I'm sure that there must be a better solution. This is what I want to do (to get all WTA and then to remove them):
List<int> cycles = scenario.Cycles.Select(x=>x.cycle_id).ToList();
List<int> activitiesForScenario = context.Activities.Where(
a=> cycles.Contains(a.Cycle.cycle_id)).Select(a=>a.activity_id).ToList();
List<WTA> wtas=
context.WTAs.Where(wta => activitiesForScenario.Contains(wta.activity_id_fk)).ToList();
foreach (Week_TSE_activities wta in weekTSEactivities)
{
context.Week_TSE_activities.Remove(wta);
}
And this is how it is right now (much better, but I don't think it's a good solution).
foreach (Cycle cycle in scenario.Cycles)
{
foreach (Activity activity in cycle.Activities)
{
activity.WTAs.Clear();
}
}
Tnks a lot for the help.
Upvotes: 0
Views: 1264
Reputation: 1347
The way I've done mass deletes using EF in the past was anything from what you've mentioned above (using a loop) to actually running a hard coded delete query using context.ExecuteStoreQuery("DELETE FROM catalog");
on the version you have with looping, it should do a mass delete once you do the context.SaveChanges() should it not?
Upvotes: 1