Last active
February 28, 2024 05:26
-
-
Save davepcallan/ee1031f39d80b6ba9bbdea15853a6ebf to your computer and use it in GitHub Desktop.
Apply global query filters automatically to all entities which implement an interface or have a particular property
This file contains 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