Entity Framework – Delete without Select

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.

Simples.

It is recommended that the Remove and 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.

MSDN Documention for Remove method

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: