Entity Framework Delete Multiple Entities Discover to Improve Delete
How to Delete Multiple Entities at Once?
When you want to delete hundreds, thousands, or millions of entities in one go.
StackOverflow Related Questions
- how to delete multiple rows of data with LINQ to EF using DbContext?
- How do I delete multiple rows in Entity Framework (without foreach)
Answer
RemoveRange
The RemoveRange method is used for deleting multiple objects from the database in one method call. The following code deletes a large number of records from the database using RemoveRange.
using (var ctx = new CustomerContext()) { var list = context.Customers.Where(c => c.CustomerID <= 500).ToList(); ctx.Customers.RemoveRange(list); ctx.SaveChanges(); }
RemoveRange removes the given collection of entities from the context underlying the set with each entity being put into the Deleted state such that it will be deleted from the database when SaveChanges is called.
But when you look at the query generated by EF, you will see multiple delete statements for each record to be deleted of a single query that will be sent to a database.
The only possibility to get one single statement that does all the deletes is to use 3rd party library such as Entity Framework Extensions.
BulkDelete
There are many solutions to delete many records in the fastest way, but the most significant and recommended solution is BulkDelete provided by Entity Framework Extensions library. By default, the identity value is populated to make it even easier to use.
using (var ctx = new CustomerContext()) { var list = context.Customers.Where(c => c.CustomerID <= 500).ToList(); ctx.BulkDelete(list); }
ZZZ Projects