This post applies to EF 4.1 and above.
The following technique is applicable to updating as well. But for a more detailed explanation, head over to Entity Framework – Update without Select.
The method used to delete an entry using Entity Framework is
DbContext.DbSet.Remove(Object entity), which accepts as it’s single parameter the entity you wish to delete. A subsequent call to .SaveChanges() on your context will perform a delete query on the database.
The code above tells the Entity Framework to produce two separate SQL queries in order to do this. One to select the entity, and then another to delete it. Since we have the primary key, all we would do in sensible reality is a single deletion query.
Thankfully, the Entity Framework doesn’t require a fully populated entity in order to produce the query. It simply needs to know which fields to match. In the case of a primary key it is safe to simply give it an empty version of the entity, with only the key populated.
It is recommended that the
SaveChanges calls above are wrapped in a try/catch block in case the deletion fails. You can catch exceptions of the type
DataException and process accordingly.