如何在Entity Framework中删除多个行(没有foreach) [英] How do I delete multiple rows in Entity Framework (without foreach)
问题描述
现在我这样做:
var widgets = context.Widgets
.Where(w => w.WidgetId == widgetId);
foreach(小部件中的Widget小部件)
{
context.Widgets.DeleteObject(widget);
}
context.SaveChanges();
它工作,但foreach错误我。我使用的是EF4,但我不想执行SQL。我只想确保我没有丢失任何东西 - 这是一样好,对吧?我可以用扩展方法或帮助器来抽象它,但是在某个地方我们仍然要做一个foreach,对吧?
如果你不想执行SQL直接在循环中调用DeleteObject是你今天可以做的最好的。但是,您可以执行SQL,但仍然可以通过扩展方法使其完全通用,使用我描述的方法这里。
尽管答案是3.5。对于4.0,我可能会使用新的ExecuteStoreCommand API,而不是下降到StoreConnection。
I'm deleting several items from a table using Entity Framework. There isn't a foreign key / parent object so I can't handle this with OnDeleteCascade.
Right now I'm doing this:
var widgets = context.Widgets
.Where(w => w.WidgetId == widgetId);
foreach (Widget widget in widgets)
{
context.Widgets.DeleteObject(widget);
}
context.SaveChanges();
It works but the foreach bugs me. I'm using EF4 but I don't want to execute SQL. I just want to make sure I'm not missing anything - this is as good as it gets, right? I can abstract it with an extension method or helper, but somewhere we're still going to be doing a foreach, right?
If you don't want to execute SQL directly calling DeleteObject in a loop is the best you can do today.
However you can execute SQL and still make it completely general purpose via an extension method, using the approach I describe here.
Although that answer was for 3.5. For 4.0 I would probably use the new ExecuteStoreCommand API under the hood, instead of dropping down to the StoreConnection.
这篇关于如何在Entity Framework中删除多个行(没有foreach)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!