用这个方法呢:modelBuilder.Entity<YourType>(m => dosomthing)
这个类似与单独指定的实体,我想要的是所有实体一起指定和过滤
可将所有实体继承于同一个类,将TenentId放到父类中。
var parameter = Expression.Parameter(item, "u");
MemberExpression entityTenantId = Expression.Property(parameter, "TenantId");
var properyName = Expression.Constant("TenantId");
var propertyValue = Expression.Call(Expression.Constant(this), this.GetType().GetMethod(nameof(GetTenantId))!);
//var left = Expression.Call(typeof(EF), nameof(EF.Property), new[] { typeof(object) }, parameter, properyName);
var left = entityTenantId;
var expressionBody = Expression.Equal(left, propertyValue);
var expression = Expression.Lambda(expressionBody, parameter);
modelBuilder.Entity(item).HasQueryFilter(expression);
通过动态生成表达式树的方法进行的,对应的条件是一个方法,这样每次调用都会取访问这个方法
类似这种
modelBuilder.SetQueryFilterOnAllEntities<ISoftDelete>(x => x.Deleted == false);
public static void SetQueryFilterOnAllEntities<TEntityInterface>(
this ModelBuilder builder,
Expression<Func<TEntityInterface, bool>> filterExpression)
{
foreach (var type in builder.Model.GetEntityTypes()
.Where(t => t.BaseType == null)
.Select(t => t.ClrType)
.Where(t => typeof(TEntityInterface).IsAssignableFrom(t)))
{
builder.Entity(type)
.AppendQueryFilter(filterExpression);
}
}
private static void AppendQueryFilter(this EntityTypeBuilder entityTypeBuilder, LambdaExpression expression)
{
var parameterType = Expression.Parameter(entityTypeBuilder.Metadata.ClrType);
var expressionFilter = ReplacingExpressionVisitor.Replace(
expression.Parameters.Single(), parameterType, expression.Body);
if (entityTypeBuilder.Metadata.GetQueryFilter() != null)
{
var currentQueryFilter = entityTypeBuilder.Metadata.GetQueryFilter();
var currentExpressionFilter = ReplacingExpressionVisitor.Replace(
currentQueryFilter.Parameters.Single(), parameterType, currentQueryFilter.Body);
expressionFilter = Expression.AndAlso(currentExpressionFilter, expressionFilter);
}
var lambdaExpression = Expression.Lambda(expressionFilter, parameterType);
entityTypeBuilder.HasQueryFilter(lambdaExpression);
}