ef core 2 对所有实体应用 HasQueryFilter [英] ef core 2 apply HasQueryFilter for all entity
问题描述
有什么方法可以将HasQueryFilter"全局应用于我的所有实体?我不要一一加入modelbuilder?
Is there any way to apply "HasQueryFilter" globaly to all my entity ? I don't want to add in modelbuilder one by one ?
modelBuilder.Entity<Manufacturer>().HasQueryFilter(p => p.IsActive);
推荐答案
如果您有定义 IsActive
属性的基类或接口,您可以使用 过滤所有查询(尝试实现软删除).
In case you have base class or interface defining the IsActive
property, you could use the approach from Filter all queries (trying to achieve soft delete).
否则,您可以迭代实体类型,并且对于每个具有 bool IsActive
属性的类型,使用 Expression
类方法构建动态过滤器表达式:
Otherwise you could iterate entity types, and for each type having bool IsActive
property build dynamically filter expression using Expression
class methods:
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
var isActiveProperty = entityType.FindProperty("IsActive");
if (isActiveProperty != null && isActiveProperty.ClrType == typeof(bool))
{
var parameter = Expression.Parameter(entityType.ClrType, "p");
var filter = Expression.Lambda(Expression.Property(parameter, isActiveProperty.PropertyInfo), parameter);
entityType.QueryFilter = filter;
}
}
更新(EF Core 3.0):由于公共元数据 API 重大更改(用 Get
/Set
扩展方法替换了许多属性),最后一行变成
Update (EF Core 3.0): Due to public metadata API breaking change (replacing many properties with Get
/ Set
extension methods), the last line becomes
entityType.SetQueryFilter(filter);
这篇关于ef core 2 对所有实体应用 HasQueryFilter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!