Skip to content

Instantly share code, notes, and snippets.

@eduardosilva
Last active April 11, 2016 18:13
Show Gist options
  • Save eduardosilva/8417389 to your computer and use it in GitHub Desktop.
Save eduardosilva/8417389 to your computer and use it in GitHub Desktop.
Dynamically load entity framework configurations.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//MyDataContext: is my current database context
var configurationTypes = typeof(DataContext).Assembly.GetTypes()
.Where(t => t.IsAbstract == false &&
t.BaseType != null &&
t.BaseType.IsGenericType &&
(t.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>) ||
t.BaseType.GetGenericTypeDefinition() == typeof(ComplexTypeConfiguration<>)))
.ToArray();
foreach (var configurationType in configurationTypes)
{
dynamic configurationTypeInstance = Activator.CreateInstance(configurationType);
modelBuilder.Configurations.Add(configurationTypeInstance);
}
base.OnModelCreating(modelBuilder);
Database.SetInitializer<DataContext>(null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment