How do I delete multiple rows in Entity Framework (without foreach)
entity-framework
Solution
This answers is for EF Core 7 (I am not aware if they merged EF Core with EF now or not, before they kept the two separately).
EF Core 7 now supports ExecuteUpdate and ExecuteDelete (Bulk updates):
// Delete all Tags (BE CAREFUL!)
await context.Tags.ExecuteDeleteAsync();
// Delete Tags with a condition
await context.Tags.Where(t => t.Text.Contains(".NET")).ExecuteDeleteAsync();
The equivalent SQL queries are:
DELETE FROM [t]
FROM [Tags] AS [t]
DELETE FROM [t]
FROM [Tags] AS [t]
WHERE [t].[Text] LIKE N'%.NET%'
Problem
I want to delete several items from a table using Entity Framework. There is no 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 the code with an extension method or helper, but somewhere we're still going to be doing a `foreach`, right?