DEV Community

An easy and simple way to implement soft delete in .Net using EF Core

When developing APIs, it's common to have to modify the behavior of DELETE so that instead of deleting a record, it simply changes a boolean property and considers that resource not to exist if the value of the property is false. This technique is known as "Soft Delete."

There are many ways to implement this behavior. The approach presented in this text can be summarized in the following steps:
1- Add a boolean property to the desired class.
2- Override the SaveChangesAsync method of the class that extends DbContext.
3- Add a filter to the entity configuration so that "inactive" entities are not returned in queries.

Add boolean property

The first step is self-explanatory. Create an entity and add the boolean property to it. If multiple entities need this behavior, consider creating a base class or interface that contains it.

Override the SaveChangesAsync method

If you use EF Core, you likely extended the DbContext class to create your context. The base class has a method called SaveChangesAsync, which saves the changes made to the database.

The following code aims to detect the state of the entities tracked by the ChangeTracker. If any has been deleted, it will change its state to Unchanged (instead of Deleted) and then change the boolean property added in the previous step.

public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
    foreach (var entry in ChangeTracker.Entries<T>()) // Where "T" is the entity type
        switch (entry.State)
            case EntityState.Deleted:
                entry.State = EntityState.Unchanged;
                entry.Entity.BooleanProperty = false; // Prefer using a method for this.
    return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
Enter fullscreen mode Exit fullscreen mode

Add filter

With the modification made, it's now possible to update all queries so they ignore entities where the value of the boolean property is false. However, depending on the size of your application, this may be a quite tedious task.

To avoid the described situation, EF provides a way to do this automatically through entity configuration. Example:

public class YourEntityConfiguration : IEntityTypeConfiguration<YourEntity>
    public void Configure(EntityTypeBuilder<YourEntity> builder)
        builder.HasQueryFilter(x => x.Active);
Enter fullscreen mode Exit fullscreen mode

The above code ensures that only entities with the Active property set to true are returned in queries.

We've reached the end of the tutorial. I hope this text has been enough to implement basic Soft Delete behavior in your application.

Top comments (0)