Delete a record without prior loading in Entity Framework

Sometimes you have an Id of an object and want to delete the underlying thing from the database. But it doesn't make sense to load the whole object from the database to memory first. So how can we achieve this quickly?

The naive approach in Entity Framework would be something like this:

public async Task Delete(int id)
{
    using var dbContext = new MyDbContext();
    var objectToDelete = await dbContext.Objects.FirstAsync(o => o.Id == id);
    dbContext.Objects.Remove(objectToDelete);
    await dbContext.SaveChangesAsync();
}

This is quite inefficient because we have to do two roundtrips. The first one is to retrieve the object in question and the second one is to delete the object. Ideally, we want to have one roundtrip and one roundtrip only - removing the object. And we can achieve this pretty easily. The only thing Entity Framework needs here is the primary key, so we can create a new object on which we set the id.

public async Task Delete(int id)
{
    using var dbContext = new MyDbContext();
    var objectToDelete = new MyObject { Id = id };
    dbContext.Objects.Remove(objectToDelete);
    await dbContext.SaveChangesAsync();
}

And voilà we are done here. One less roundtrip to the database (thanks to @latonz for pointing that out).

The same you can do even easier and in one simple line with .NET7:

public async Task Delete(int id)
{
   await dbContext.Objects.Where(x => x.Id == id).ExecuteDeleteAsync();
}
3
An error has occurred. This application may no longer respond until reloaded. Reload x