.NET Tips and Tricks

Blog archive

Save Some Time Deleting Entities in Entity Framework: RemoveRange

When it comes to speeding up your application, your best opportunity is to reduce trips to your database. So, when you see a method like RemoveRange on a DbContext collection, you might think that's an opportunity to delete a bunch of objects in less time than deleting those same objects one by one. You'd be right…but not because you're saving trips to your database.

Here's some sample code that will delete all of the SalesOrderHeaders with a DueDate before the current date:

Dim res = From so In db.SalesOrderHeaders 
          Where so.DueDate < DateTime.Now 
          Select so 
db.SalesOrderHeaders.RemoveRange(res)  
db.SaveChanges

This will run faster than, for example, looping through the res collection and passing each object to the SalesOrderHeaders Remove method before calling SaveChanges. However, either way, you'll still be making one trip to the database, submitting one SQL delete statement for every SalesOrderHeader that's being deleted.

Where you'll save time is in the overhead around removing the objects from the SalesOrderHeaders collection (especially around change tracking which will run once with RemoveRange rather than once for each object with Remove).

Posted by Peter Vogel on 06/21/2016


comments powered by Disqus

Featured

Subscribe on YouTube