Many Web programs in general will not be designed to be really physically removed.
It’s basically just adding a marker to the database, and it’s supposed to be deleted. At the same time, when querying, filter the data that has been marked for deletion
Ef Core soft delete is very simple to implement. It dynamically creates an IsDeleted field in OnModelCreating, which is of type BOOL. And then throw it into the EF Core query filter.
protected override void OnModelCreating(ModelBuilder modelBuilder) { foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { entityType.GetOrAddProperty("IsDeleted", typeof(bool)); var parameter = Expression.Parameter(entityType.ClrType); var propertyMethodInfo = typeof(EF).GetMethod("Property").MakeGenericMethod(typeof(bool)); var isDeletedProperty = Expression.Call(propertyMethodInfo, parameter, Expression.Constant("IsDeleted")); BinaryExpression compareExpression = Expression.MakeBinary(ExpressionType.Equal, isDeletedProperty, Expression.Constant(false)); var lambda = Expression.Lambda(compareExpression, parameter); modelBuilder.Entity(entityType.ClrType).HasQueryFilter(lambda); }}Copy the code
Then, when saving the Deleted entity, scan for changes and change the status of the Deleted entity to Modified with a value of false for IsDeleted.
ChangeTracker.DetectChanges();
foreach (var item in ChangeTracker.Entries().Where(e => e.State == EntityState.Deleted))
{
item.State = EntityState.Modified;
item.CurrentValues["IsDeleted"] = true;
}
Copy the code
This can be done in EF no perception soft delete!
To query for soft deleted data in a query, simply add IgnoreQueryFilters
blogs = db.Blogs
.Include(b => b.Posts)
.IgnoreQueryFilters()
.ToList();
Copy the code
This will query the soft delete data.