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.