.NET Tips and Tricks

Blog archive

Save a Trip to the Database with Deletes in Entity Framework

In both deletes and updates there's an assumption that you have to retrieve the corresponding entity object from the database. With an update, you pull back the object so that you can set its properties; with a delete, you retrieve the object so that you can pass it to the corresponding collection's Remove method. That delete code might look like this, for example:

Dim cust As Customer
cust = db.Customers.Find("A123")
db.Customers.Remove(cust)
db.SaveChanges

You don't have to actually need to make that first trip to the database. For a delete, for example, all you have to do is convince Entity Framework's change tracking mechanism that you've deleted the object ... and that just means that you have to remove an object with the right values in the primary key properties. This code, for example:

Dim cust As New Customer
cust.CustId = "A123"
db.Customers.Attach(cust)
db.Customers.Remove(cust)
db.SaveChanges()

will delete Customer A123 from the database without having to retrieve it.

Posted by Peter Vogel on 06/03/2016


comments powered by Disqus

Featured

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

  • Introduction to .NET Aspire

    Two Microsoft experts will present on the cloud-native application stack designed to simplify the development of distributed systems in .NET at the Visual Studio Live! developer conference coming to Las Vegas next month.

  • Microsoft Previews Copilot AI for Open-Source Eclipse IDE

    Catering to Java jockeys, Microsoft is yet again expanding the sprawling reach of its Copilot-branded AI assistants, previewing a coding tool for the open-source Eclipse IDE.

Subscribe on YouTube

Upcoming Training Events