ef核心2将HasQueryFilter应用于所有实体 [英] ef core 2 apply HasQueryFilter for all entity
问题描述
是否可以将 HasQueryFilter全局应用于我的所有实体?我不希望
一一添加到模型构建器中?
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核心2将HasQueryFilter应用于所有实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!