码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-11-10 19:27:40      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:cme   eof   tde   ted   extension   odi   sig   type   inf   

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

 

 

 

 

 

 

 

 

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

标签:cme   eof   tde   ted   extension   odi   sig   type   inf   

原文地址:https://www.cnblogs.com/Spinoza/p/11831205.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!