.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

  • Full Stack Hands-On Development with .NET

    In the fast-paced realm of modern software development, proficiency across a full stack of technologies is not just beneficial, it's essential. Microsoft has an entire stack of open source development components in its .NET platform (formerly known as .NET Core) that can be used to build an end-to-end set of applications.

  • .NET-Centric Uno Platform Debuts 'Single Project' for 9 Targets

    "We've reduced the complexity of project files and eliminated the need for explicit NuGet package references, separate project libraries, or 'shared' projects."

  • Creating Reactive Applications in .NET

    In modern applications, data is being retrieved in asynchronous, real-time streams, as traditional pull requests where the clients asks for data from the server are becoming a thing of the past.

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

Subscribe on YouTube