Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - delete a record with the primary key

Is there a way to delete a record by its primary key?

Yes I know I can do the following:

using (var context = new MyDbContext())
{
    var entity = context.MyEntity.Find(id);
    context.MyEntity.Remove(entity);
    context.SaveChanges();
}

But I prefer to not incur the unnecessary overhead of loading the record first.

I am aware of this question but it is 11 years old and I'm hoping there's been a solution for this added since then.

like image 835
David Thielen Avatar asked Jun 19 '26 12:06

David Thielen


1 Answers

Nope, still about the quickest way to delete an entity without the round-trip. However there is one important detail if using something like an injected DbContext:

For instance, the following code is perfectly fine with a scoped DbContext:

using (var context = new AppDbContext())
{
    var entityToDelete = new MyEntity { Id = idToDelete };
    context.Attach(entityToDelete);
    context.MyEntities.Remove(entityToDelete);
    context.SaveChanges();
}

But with an injected DbContext, attaching an entity can result in an exception if the DbContext happens to be already tracking an entity with that ID. This can result in situational runtime exceptions. The correct approach without a round trip with an injected DbContext would be:

var entityToDelete = context.MyEntities.Local.FirstOrDefault(x => x.Id == idToDelete);
if(entityToDelete == null)
{
    entityToDelete = new MyEntity { Id = idToDelete };
    context.Attach(entityToDelete);
}
context.MyEntities.Remove(entityToDelete);
context.SaveChanges();

We need to check the local tracking cache prior to attaching an entity. If we are tracking that desired entity, we remove that instance, otherwise we can go ahead and attach a new dummy record.

like image 109
Steve Py Avatar answered Jun 21 '26 01:06

Steve Py