当用户为admin时包含IsDeleted值

dar*_*win 3 c# lambda entity-framework-core

isDeleted当用户是管理员时,我想将数据库中的值包括到索引中。我使用了全局查询过滤器来过滤数据。

这是我的代码:

var param = Expression.Parameter(entity.ClrType);

var propertyMethodInfo = typeof(EF).GetMethod("Property").MakeGenericMethod(typeof(bool));
var isDeleted = Expression.Call(propertyMethodInfo, param, Expression.Constant("IsDeleted"));

BinaryExpression compareExpression = Expression.MakeBinary(ExpressionType.Equal, isDeleted, Expression.Constant(false));

var lambdaExpression = Expression.Lambda(compareExpression, param);

builder.Entity(entity.ClrType).HasQueryFilter(lambdaExpression);
Run Code Online (Sandbox Code Playgroud)

Iva*_*oev 5

解决方案是向全局查询过滤器添加其他条件,并确保对其进行动态评估。全局查询过滤器示例中基本解释了该技术:

小费

请注意DbContext实例级别字段的使用:_tenantId用于设置当前租户。模型级过滤器将使用正确上下文实例中的值。即正在执行查询的实例。

基本部分是使用您的实例字段/属性/方法DbContext,否则过滤器将不是动态的。

然后,将一个字段添加到您的DbContext

bool includeDeleted = false;
Run Code Online (Sandbox Code Playgroud)

并修改您的代码以产生p => this.includeDeleted || p.IsDeleted == false

// ...

var includeDeleted = Expression.Field(Expression.Constant(this), "includeDeleted");
var condition = Expression.OrElse(includeDeleted, compareExpression);

var lambdaExpression = Expression.Lambda(condition, param);

builder.Entity(entity.ClrType).HasQueryFilter(lambdaExpression);
Run Code Online (Sandbox Code Playgroud)

您如何填充该字段取决于您。可以通过构造函数参数/注入,公共属性等。