Delete a single record from Entity Framework?

user2497476 picture user2497476 · Jul 18, 2013 · Viewed 335.8k times · Source

I have a SQL Server table in Entity Framework named employ with a single key column named ID.

How do I delete a single record from the table using Entity Framework?

Answer

mt_serg picture mt_serg · Jul 18, 2013

It's not necessary to query the object first, you can attach it to the context by its id. Like this:

var employer = new Employ { Id = 1 };
ctx.Employ.Attach(employer);
ctx.Employ.Remove(employer);
ctx.SaveChanges();

Alternatively, you can set the attached entry's state to deleted :

var employer = new Employ { Id = 1 };
ctx.Entry(employer).State = EntityState.Deleted;
ctx.SaveChanges();