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();
}

Entity Framework and ordered indexes

In Entity Framework 7, the team has added support for ordered indexes to the fluent API. In this blog post we will look at how to use this feature and what it means for your database.

Entity Framework - Storing complex objects as JSON

From time to time, it is nice to store complex objects or lists as JSON in the database. With Entity Framework 8, this is now easily possible. But this was possible all along with Entity Framework 7.

Entity Framework 8: Raw SQL queries on unmapped types

The next iteration of Entity Framework, namely Entity Framework 8, will have a new and exciting feature:

Support raw SQL queries without defining an entity type for the result

That means less boilerplate code!

An error has occurred. This application may no longer respond until reloaded. Reload x