terça-feira, 14 de janeiro de 2014

Carregando dinamicamente as configurações do Entity Framework Code First

Abaixo um exemplo de como carregar as configurações customizadas de mapeamentos para o Entity Framework Code First.

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);
}
view raw gistfile1.cs hosted with ❤ by GitHub

Nenhum comentário: