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?
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.
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");
EntityFramework 6 has made this a bit easier with .RemoveRange()
.
Example:
db.People.RemoveRange(db.People.Where(x => x.State == "CA")); db.SaveChanges();
using (var context = new DatabaseEntities()) { context.ExecuteStoreCommand("DELETE FROM YOURTABLE WHERE CustomerID = {0}", customerId); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With