Entity Framework: Delete Entity by Id - Using Detached Instance

Entity Framework 5, with the Code First approach can do some pretty powerful things without much effort. Create your model classes, and it spins up a brand new and shiny database for you.

But sometimes you do need to tweak a few things in order to achieve what you want. For example, I don’t want to load an entity before I can delete it. What’s the point? Say I have a list of Accounts on a webpage, with a shiny delete button that makes an AJAX call to an MVC controller, (or Backbone model, that hits the web backend). In that situation I’ll only have the Id of the entity, which should be enough to delete it.

Attach, Delete

To delete only by Id, you need to create a dummy instance of your model with the Id you wish to delete.

Account account = new Account { Id = 123 };

Then, with EF5 you will have to attach the entity to its DbSet.

this.DbContext.Accounts.Attach(account);

Then mark it as deleted, and save the changes.

this.DbContext.Entry(account).State = EntityState.Deleted; this.DbContext.SaveChanges();