ef 通过反射和表达式树配置全局过滤筛选器

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();

 

 

 

 

 

 

 

 

猜你喜欢

转载自www.cnblogs.com/Spinoza/p/11831205.html