Soft Deletes with Entity Framework Core 2 – Part 2
Update: see part 3 here.
My previous post explained how to setup soft deletes for queries automatically. This time, I’m going to talk about the other part: actually replacing a delete for an update that sets the is deleted column.
The key here is to intercept the SaveChanges method, find out all entities that are ISoftDeletable and are marked for deletion and then set their IsDeleted property and change their state to be modified instead of deleted:
public override int SaveChanges()
{
foreach (var entry in this.ChangeTracker.Entries<ISoftDeletable>().Where(e => e.State == EntityState.Deleted))
{
entry.Property(_isDeletedProperty).CurrentValue = true;
entry.State = EntityState.Modified;
}
return base.SaveChanges();
}
This way EF Core will know what to do and just update them instead of deleting them. Next time, they won’t be loaded as they have been marked as deleted. The problem with this approach is that we have to override the SaveChanges method, this is because EF Core doesn't expose events yet. More on this on posts to come.