Entity-framework – How to delete multiple rows in Entity Framework (without foreach)

entity-framework

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?

Best Answer

EntityFramework 6 has made this a bit easier with .RemoveRange().

Example:

db.People.RemoveRange(db.People.Where(x => x.State == "CA"));
db.SaveChanges();