0

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.

David Thielen
  • 28,723
  • 34
  • 119
  • 193

1 Answers1

0

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.

Steve Py
  • 26,149
  • 3
  • 25
  • 43
  • Thanks. And I'm doing scoped `IDbContextFactory` objects and every `DbContext` I create is in a `using { ... }` to avoid all the problems that come with a long-lived DbContext. thanks – David Thielen Jun 05 '23 at 21:07