In Entity Framework, how can I remove many rows? (without foreach)

entity-framework

Question

I'm using Entity Framework to remove a number of objects from a table. Since there is no parent object or foreign key, I am unable to manage this using OnDeleteCascade.

What I'm doing right now is

var widgets = context.Widgets
    .Where(w => w.WidgetId == widgetId);

foreach (Widget widget in widgets)
{
    context.Widgets.DeleteObject(widget);
}
context.SaveChanges();

It works, however I don't like the approach. Although I'm using EF4, I don't want to run SQL. This must be the best there is, right? I just want to be sure I'm not missing anything. I can use an extension method or helper to encapsulate it, but somewhere we'll still be running a foreach, am I right?

1
301
3/25/2010 10:24:26 PM

Accepted Answer

The best you can do right now is call DeleteObject in a loop if you don't want to directly run SQL.

However, by utilizing the extension mechanism I explain here, you may run SQL while keeping it entirely general purpose.

Nevertheless, the answer was for 3.5. Instead of reverting to the StoreConnection for 4.0, I would likely utilize the new ExecuteStoreCommand API.

49
5/23/2017 12:26:34 PM

Popular Answer

With EntityFramework 6, this has been somewhat simplified..RemoveRange() .

Example:

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow