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.