In this demo we will examine how to override the SaveChanges method of the DbContext class in order to implement a soft-delete functionality in Entity Framework Core 3.1.
Soft-delete means that, instead of deleting database records, you’ll “mark them” as deleted. This can be accomplished by having some sort of “IsDeleted” column and setting it to true.
We want that anytime we try to delete any entity with the column “IsDeleted”, we instead update that column value to true.
Example
One way of doing this is by overriding the SaveChanges method, like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public override int SaveChanges() | |
{ | |
// Soft-Delete | |
var entities = ChangeTracker.Entries() | |
.Where(e => e.State == EntityState.Deleted && e.Metadata.GetProperties() | |
.Any(x => x.Name == "IsDeleted")) | |
.ToList(); | |
foreach (var entity in entities) | |
{ | |
entity.State = EntityState.Unchanged; | |
entity.CurrentValues["IsDeleted"] = true; | |
} | |
return base.SaveChanges(); | |
} |
You have to put this code in the class in your project that inherits from DbContext.
So, now if you have an entity or model that have the IsDeleted property, then it will automatically have the soft-delete functionality. Example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Student { | |
public int Id { get; set; } | |
public string Name { get; set; } | |
public int Age { get; set; } | |
public bool IsDeleted { get; set; } | |
} |
If you don’t want to use soft-delete, then just don’t add an IsDeleted column to your entity.
Summary
With soft-delete you don’t delete entities, but update a column indicating that the entity is deleted. So you update instead of delete. You can use this to avoid deleting data that you may want to use later. Override the SaveChanges method to accomplish this as showed in this post.