1.软删除接口
1 public interface ISoftDelete 2 { 3 bool IsDeleted { get; set; } 4 }
2.实体类实现
1 public class TestDeleted:ISoftDelete 2 { 3 public int Id { get; set; } 4 5 public string Name { get; set; } 6 public bool IsDeleted { get; set; } 7 8 9 }
3.modelBuilder扩展类
1 public static class CustomModelBuilderExtensions 2 { 3 public static void AddSoftDeleted(this ModelBuilder builder) 4 { 5 var entityTypes = builder.Model.GetEntityTypes().Where(e => typeof(ISoftDelete).IsAssignableFrom(e.ClrType)); 6 foreach (var entityType in entityTypes) 7 { 8 var parameter = Expression.Parameter(entityType.ClrType); 9 10 var propertyMethodInfo = typeof(EF).GetMethod("Property").MakeGenericMethod(typeof(bool)); 11 12 var isDeletedProperty = Expression.Call(propertyMethodInfo, parameter, Expression.Constant("IsDeleted")); 13 14 BinaryExpression compareExpression = Expression.MakeBinary(ExpressionType.Equal, isDeletedProperty, Expression.Constant(false)); 15 16 var lambdaExpression = Expression.Lambda(compareExpression, parameter); 17 18 builder.Entity(entityType.ClrType).HasQueryFilter(lambdaExpression); 19 } 20 } 21 }
4.迁移数据库
5.在OnModelCreating方法中使用全局筛选方法
1 builder.AddSoftDeleted();
6.综上所述,如果想要对一张表应用软删除的话,不是对实体类加IsDeleted字段再配置,而是让他直接实现ISoftDelete接口,这样配置更灵活