Skip to content

Instantly share code, notes, and snippets.

@kentkost
Created May 5, 2022 11:58
Show Gist options
  • Save kentkost/7b0d5201441fd3a535e869178ef83297 to your computer and use it in GitHub Desktop.
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
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