Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete multiple rows in Entity Framework (without foreach)

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?

like image 519
Jon Galloway Avatar asked Mar 25 '10 22:03

Jon Galloway


People also ask

How do I delete a row in Entity Framework?

In Connected Scenario, you can use the Remove or RemoveRange method to mark the record as Deleted . In Disconnected Scenario, you can attach it to the context and set its state as Deleted . Calling SaveChanges will send the delete query to the database.

How do I delete all records from a table in Entity Framework?

The Other quickest simple option to delete all the rows in a table in entity framework is to use the TRUNCATE table query and execute it with the ExecuteSqlCommand as shown below. dbContext. Database. ExecuteSqlCommand("TRUNCATE TABLE Customer");


2 Answers

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

Example:

db.People.RemoveRange(db.People.Where(x => x.State == "CA")); db.SaveChanges(); 
like image 119
Kyle Avatar answered Oct 21 '22 20:10

Kyle


using (var context = new DatabaseEntities()) {     context.ExecuteStoreCommand("DELETE FROM YOURTABLE WHERE CustomerID = {0}", customerId); } 
like image 41
Vlad Bezden Avatar answered Oct 21 '22 21:10

Vlad Bezden