Soft delete with Entity Framework

In many of the applications we build, our users can delete items that are no longer needed. That's great because it gives them lots of autonomy. But sometimes the users aren't thinking hard enough (are they even thinking at all?) before deleting something they think they no longer needed. In that case they contact you and give you some weird reason why they deleted it and then the'll ask you to restore it. If you are a good person and keep daily backups of your applications, then you can go and find the backup and restore the lost data. But even if you have backups it may require lots of work for you to restore that one record without overriding any other changes the user has made. That's why I tend to always implement soft delete in my applications. Pretty much all of my entities will have a property "IsDeleted" of some sort. This field allows me to restore a deleted item in no time. Great, but sometimes these properties can add lots of complexity to our repositories which will cause bugs over time. In this post I'll show you how to implement Soft Delete without adding any complexity to your repositories!

I have added a where clause to exclude the deleted lessons. Lets try again!

As you can see, the lesson about Artificial Intelligence is no longer visible! But if we take a closer look, we notice that some of the students that show up are actually deleted and they shouldn't be there! Let's fix this.

I have added a foreach loop to exclude all the deleted students from the lessons. This should fix our issue! We'll give this a try.

Great! our deleted students no longer appear in the list!

Now, what if we want to create a GetLessonById method? Easy, we filter the students from that lesson!

But wait, What if we have lots of other queries? What if our teacher is deleted? What if our students can each have a set of Skills that can be deleted? This will add lots of repetitive code and complexity. There must be a better solution, right?!

Dynamic filters

Lucky for us there is a nuget package we can use that will make our lives a lot easier! Let's take a look at EntityFramework.DynamicFilters. Using this nuget package we can define global filters to our context! For example we can tell our context not to use our deleted entities. Let's implement this!

First install the package

Install-Package EntityFramework.DynamicFilters

Next, define the global filter, add the following line to the OnModelCreating method of our context:

Nice and clean, and when we run our application again we get the following result:

No deleted records, great!

Conclusion

As you can see using these dynamic filters it is really easy to implement soft delete in any application using Entity Framwork. The nuget package I have used here has lot's of other great features so make sure you check it out and find which ones will work in your applications!

Thanks for reading, and leave a comment below if you have any questions or suggestions!