Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: How do I delete a record by its primary key?

How do I delete a record by its primary key without first doing a SELECT statement to load the entity?

like image 416
Jonathan Allen Avatar asked Dec 05 '11 20:12

Jonathan Allen


2 Answers

You can use dummy object:

var entity = new YourEntity { Key = yourKey };
context.Entities.Attach(entity);
context.Entities.DeleteObject(entity);
context.SaveChanges();
like image 79
Ladislav Mrnka Avatar answered Oct 08 '22 19:10

Ladislav Mrnka


Which version of the Entity Framework are you using?

If you're using Entity Framework 4.1 or above, and using the DbContext class, you can use the ExecuteSqlCommand() method to send a DELETE statement to the database. See http://blogs.msdn.com/b/adonet/archive/2011/02/04/using-dbcontext-in-ef-feature-ctp5-part-10-raw-sql-queries.aspx (look at the Sending Raw Commands to the Database section). This will look something like:

DbContext ctx = ... get your DbContext somehow...
ctx.Database.ExecuteSqlCommand("DELETE FROM Foo WHERE FooID = 17");

If you're using Entity Framework 4.0 and ObjectContext (instead of DbContext) there's a similar ExecuteStoreCommand method (http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.executestorecommand.aspx).

like image 45
triangle_man Avatar answered Oct 08 '22 18:10

triangle_man