Soft delete with entity framework core

Soft delete means mark it as deleted, don’t completely remove it from database (db) is a common way to achieve the “delete - restore” pattern. It’s very easy to do that in Entity Framework Core, combine with repository pattern. Let’s see how in this post.

Models

Say we have a simple database structure like below:

here we have 2 tables and One to Many relationship. You can leave them and let EF handle the relationship for you as it uses naming convention.

The db context should simple as well:

Enable soft delete entity

Okay now let’s add soft delete to our entity. I can add to each entity a property but I won’t, let’s keep it clean and DRY. So I’ll create a base entity:

That’s all. You can now imagine that if DeletedAt not null then it’s deleted. You can also use bool or whatever fit your business.

Soft delete query

Without doing anything else, you can query entities not deleted by a simple condition:

but things getting complicated as you have to check DeletedAt prop all the time. See a complex long query below to just achieve a simple requirement - get product in a specific category:

LOL, too much query. But don’t worry, EF has a super cool feature to help you query as normal. Let’s see how.

I’ll create entity configuration for all entity:

IEntityTypeConfiguration is new interface in EF Core to build fluent configuration for entity. With HasQueryFilter EF with generates query with a default filter:

To apply this config, add it in OnModelCreating in db context:

now your query is much more simple:

How to soft delete?

Just set DeletedAt not null, so we no longer use delete query anymore:

That’s all. In next post I’ll show you more things like how to unapply the default filter, combining with repository pattern for less code..etc. Stay tuned.

P/S: I’ll translate into Vietnamese soon, or help me by create a PR at my blog. Thank you.