Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davepcallan/b8a23dee9035879e2e5a15552211c2e6 to your computer and use it in GitHub Desktop.
Save davepcallan/b8a23dee9035879e2e5a15552211c2e6 to your computer and use it in GitHub Desktop.
Apply global filters in Entity Framework
public static void ApplyGlobalFilters<TInterface>(this ModelBuilder modelBuilder,
Expression<Func<TInterface, bool>> expression)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (entityType.ClrType.GetInterface(typeof(TInterface).Name) != null)
{
var newParam = Expression.Parameter(entityType.ClrType);
var newbody = ReplacingExpressionVisitor.
Replace(expression.Parameters.Single(), newParam, expression.Body);
modelBuilder.Entity(entityType.ClrType).
HasQueryFilter(Expression.Lambda(newbody, newParam));
}
}
}
public static void ApplyGlobalFilters<T>(this ModelBuilder modelBuilder,
string propertyName, T value)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
var foundProperty = entityType.FindProperty(propertyName);
if (foundProperty != null && foundProperty.ClrType == typeof(T))
{
var newParam = Expression.Parameter(entityType.ClrType);
var filter = Expression.
Lambda(Expression.Equal(Expression.Property(newParam, propertyName),
Expression.Constant(value)), newParam);
modelBuilder.Entity(entityType.ClrType).HasQueryFilter(filter);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment