Created
March 1, 2023 21:24
-
-
Save davepcallan/b8a23dee9035879e2e5a15552211c2e6 to your computer and use it in GitHub Desktop.
Apply global filters in Entity Framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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