简体   繁体   中英

Clear list of entity objects (C# and entity framework 4)

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM