[英]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):
这就是我想要做的(获取所有 WTA,然后删除它们):
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");
我过去使用 EF 进行批量删除的方式是从您上面提到的(使用循环)到使用
context.ExecuteStoreQuery("DELETE FROM catalog");
实际运行硬编码删除查询的任何方式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?在您使用循环的版本上,一旦您执行 context.SaveChanges() 应该不会进行批量删除吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.