13

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

Jonathan Allen
  • 66,142
  • 66
  • 246
  • 435

3 Answers3

21

You can use dummy object:

var entity = new YourEntity { Key = yourKey };
context.Entities.Attach(entity);
context.Entities.DeleteObject(entity);
context.SaveChanges();
Ladislav Mrnka
  • 355,666
  • 57
  • 651
  • 662
  • 7
    As of EF 5.0 you need to use context.Entities.Remove(entity); instead of context.Entities.DeleteObject(entity); – Gabriel Sep 10 '12 at 06:29
3

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).

triangle_man
  • 1,042
  • 6
  • 10
1

Depending on when you're reading this, verify the state of this ticket before implementing any hacks.

tne
  • 6,665
  • 2
  • 40
  • 65