如何在.net核心上创建2个过滤器(IsDeleted,IsActive)?

时间:2019-05-17 10:11:37

标签: asp.net-core entity-framework-core

使用HasQueryFilter时,无法禁用其中一个过滤器 在MVC中,我使用了DynamicFilter,并为每个过滤器选择了一个名称,所有过滤器都将在运行时被禁用。 .net核心中是否有方法?

        private LambdaExpression SetSoftDeleteQueryFilter(IMutableEntityType entityType)
        {
            var parameter = Expression.Parameter(entityType.ClrType);

            var propertyMethodInfo = typeof(EF).GetMethod("Property").MakeGenericMethod(typeof(bool));
            var isDeletedProperty = Expression.Call(propertyMethodInfo, parameter, Expression.Constant("IsDeleted"));
            var compareExpression = Expression.MakeBinary(ExpressionType.Equal, isDeletedProperty, Expression.Constant(false));
            return Expression.Lambda(compareExpression, parameter);
        }

        private LambdaExpression SetActiveQueryFilter(IMutableEntityType entityType)
        {
            var parameter = Expression.Parameter(entityType.ClrType);

            var propertyMethodInfo = typeof(EF).GetMethod("Property").MakeGenericMethod(typeof(bool));
            var isDeletedProperty = Expression.Call(propertyMethodInfo, parameter, Expression.Constant("IsActive"));
            var compareExpression = Expression.MakeBinary(ExpressionType.Equal, isDeletedProperty, Expression.Constant(true));
            return Expression.Lambda(compareExpression, parameter);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Price>().HasOne(row => row.Product).WithMany(row => row.Prices).HasForeignKey(row => row.ProductId);

            foreach (var entityType in modelBuilder.Model.GetEntityTypes())
            {
                var lambdaExpression = SetSoftDeleteQueryFilter(entityType);
                modelBuilder.Entity(entityType.ClrType).HasQueryFilter(lambdaExpression);

                lambdaExpression = SetActiveQueryFilter(entityType);
                modelBuilder.Entity(entityType.ClrType).HasQueryFilter(lambdaExpression);
            }
        }

0 个答案:

没有答案