.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

  • IDE Irony: Coding Errors Cause 'Critical' Vulnerability in Visual Studio

    In a larger-than-normal Patch Tuesday, Microsoft warned of a "critical" vulnerability in Visual Studio that should be fixed immediately if automatic patching isn't enabled, ironically caused by coding errors.

  • Building Blazor Applications

    A trio of Blazor experts will conduct a full-day workshop for devs to learn everything about the tech a a March developer conference in Las Vegas keynoted by Microsoft execs and featuring many Microsoft devs.

  • Gradient Boosting Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the gradient boosting regression technique, where the goal is to predict a single numeric value. Compared to existing library implementations of gradient boosting regression, a from-scratch implementation allows much easier customization and integration with other .NET systems.

  • Microsoft Execs to Tackle AI and Cloud in Dev Conference Keynotes

    AI unsurprisingly is all over keynotes that Microsoft execs will helm to kick off the Visual Studio Live! developer conference in Las Vegas, March 10-14, which the company described as "a must-attend event."

  • Copilot Agentic AI Dev Environment Opens Up to All

    Microsoft removed waitlist restrictions for some of its most advanced GenAI tech, Copilot Workspace, recently made available as a technical preview.

Subscribe on YouTube