EFCore批量实现全局查询筛选器
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>().Property<string>("_tenantId").HasColumnName("TenantId");
// Configure entity filters
modelBuilder.Entity<Blog>().HasQueryFilter(b => EF.Property<string>(b, "_tenantId") == _tenantId);
modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted);
}
官方的做法要一个一个的写,很麻烦。我给大家介绍一种批量实现全局查询筛选器的方法
首先定义一个通用的接口
public interface IAudit
{
public DateTime CreationTime { get; set; }
public DateTime? DeletionTime { get; set; }
public DateTime? LastModificationTime { get; set; }
public bool IsDeleted { get; set; }
}
public class AuditModel : IAudit
{
public DateTime CreationTime { get; set; }
public DateTime? DeletionTime { get; set; }
public DateTime? LastModificationTime { get; set; }
public bool IsDeleted { get; set; }
}
public class Article:AuditModel
{
public int TagId { get; set; }
public string Title { get; set; }
public int Support { get; set; }
public int Comment { get; set; }
public int Visited { get; set; }
public string Digest { get; set; }
public string Url { get; set; }
public Tag Tag { get; set; }
}
然后实现接口,并根据需求继承实现接口的类,这里我让Article类继承。
var entityTypeList = modelBuilder.Model.GetEntityTypes().Where(x => typeof(IAudit).IsAssignableFrom(x.ClrType));
foreach (var entityType in entityTypeList)
{
var parameter = Expression.Parameter(entityType.ClrType);
var propertyMethodInfo = typeof(EF).GetMethod("Property").MakeGenericMethod(typeof(bool));
var isDeletedProperty = Expression.Call(propertyMethodInfo, parameter, Expression.Constant("IsDeleted"));
BinaryExpression compareExpression = Expression.MakeBinary(ExpressionType.Equal, isDeletedProperty, Expression.Constant(false));
var lambdaExpression = Expression.Lambda(compareExpression, parameter);
modelBuilder.Entity(entityType.ClrType).HasQueryFilter(lambdaExpression);
}
这样就可以为所有实现了Iautdit接口的类定义一个全局查询筛选器(我这里是筛选出Isdelete为flase的数据);