EntityFramework Core Migration (Code First) — Part II: Soft Delete Handling

Chewy2Theo
2 min readMay 29, 2021

In case you don’t know what soft delete is, it’s the strategy of adding a IsDeleted flag in all your tables. Instead of actually deleting the row, you’ll mark the IsDeleted flag as true. But this brings forth a question, whenever I query someone from the database, do I want to include the condition where(x => x.IsDeleted == false) in every Linq that I write? Of course not, this is why this soft delete handling is implemented so that whenever I query these records EF can handle these soft deleted records for me.

How it was done in .Net

The way I impelmented soft delete in .Net is to inherit BaseEntity Class for all my entity classes. With the below configuration, EF will only retrieve the records where IsDeleted is false. By default EF does not suppor this Filter extension, this is done through the help of DynamicFilters.

using EntityFramework.DynamicFilters;protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Filter("IsDeleted", (BaseEntity d) => d.IsDeleted, false);
}

How it is now done in .Net Core

As of the time when the article above was written, the DynamicFilters Library for EF did not support EF Core. But no worries because EF Core now supports this kind of soft delete internally and will no longer need to depend on third party for this kind of handling.

First create the extension class below.

The extension class above need to work with an interface. If all your classes already inherit from a base class then you can simply create an IDelete interface with bool IsDeleted. Then you can apply the global filter below.

modelBuilder.ApplyGlobalFilters<IDelete>(e => e.IsDeleted == false);

Below is the source where I got the code from:

https://spin.atomicobject.com/2019/01/29/entity-framework-core-soft-delete/#:~:text=Soft%20Delete%20in%20EF%20Core&text=Adding%20a%20soft%20delete%20query,incorporate%20your%20soft%20delete%20functionality.&text=The%20above%20code%20intercepts%20any,the%20isDeleted%20column%20to%20true%20.

This article is a part of the .Net to .Net Core Migration Series
https://theochiu2010.medium.com/net-to-net-core-migration-2eb31584f95c

--

--

Chewy2Theo

Just another developer who's into lazy tools that can make my life easier, and hopefully yours too.