Last active
December 27, 2015 15:29
-
-
Save gabrieljoelc/7348283 to your computer and use it in GitHub Desktop.
How to scan for and add EntityTypeConfigurations for Entity Framework. From http://romiller.com/2012/03/26/dynamically-building-a-model-with-code-first/
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 class FooContext : DbContext | |
{ | |
protected override void OnModelCreating(DbModelBuilder modelBuilder) | |
{ | |
AddExplicitMappings(modelBuilder); | |
} | |
private static void AddExplicitMappings(DbModelBuilder modelBuilder) | |
{ | |
var addMethod = typeof (ConfigurationRegistrar) | |
.GetMethods() | |
.Single(m => m.Name == "Add" && m.GetGenericArguments().Any(a => a.Name == "TEntityType")); | |
// use this to debug | |
//if (System.Diagnostics.Debugger.IsAttached == false) | |
// System.Diagnostics.Debugger.Launch(); | |
var entityTypeConfigs = FindEntityTypeConfigs(); | |
entityTypeConfigs.ForEach(entityConfigType => | |
{ | |
var genericType = entityConfigType.BaseType.GetGenericArguments().Single(); | |
var entityConfig = Activator.CreateInstance(entityConfigType); | |
addMethod.MakeGenericMethod(genericType).Invoke(modelBuilder.Configurations, new[] {entityConfig}); | |
}); | |
} | |
private static IEnumerable<Type> FindEntityTypeConfigs() | |
{ | |
return Assembly.GetAssembly(typeof(FooContext)) | |
.GetTypes() | |
.Where(t => !string.IsNullOrEmpty(t.Namespace) && t.Namespace.Equals(typeof (FooBarMap).Namespace) && | |
// can't use Type::IsAssignableFrom(). use method in: https://gist.github.com/gabrieljoelc/5706069 | |
typeof(EntityTypeConfiguration<>).IsGenericTypeAssignableFrom(t)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment