Created
May 5, 2022 11:58
-
-
Save kentkost/7b0d5201441fd3a535e869178ef83297 to your computer and use it in GitHub Desktop.
This is an extension to DbContext. Where it only adds Configurations that are DbSets in the DbContext
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 class ModelBuilderExtensions | |
{ | |
//Only add the IEntityTypeConfigurations that are in the DataContext | |
public static void ApplyConfigurationsForEntitiesInContext(this ModelBuilder modelBuilder) | |
{ | |
var types = modelBuilder.Model.GetEntityTypes().Select(t => t.ClrType).ToHashSet(); | |
modelBuilder.ApplyConfigurationsFromAssembly( | |
Assembly.GetExecutingAssembly(), | |
t => t.GetInterfaces() | |
.Any(i => i.IsGenericType | |
&& i.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>) | |
&& types.Contains(i.GenericTypeArguments[0])) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment