do.Develop();

this.AreaOfInterest = Development.All();

Dynamically load Entity Configurations in EF CodeFirst CTP5

Dynamically load your EF Code First Configurations is a little more tricky with the new CTP5 since the EntityTypeConfiguration’s base type is not a generic typed class.
In CTP4 EntityConfiguration<> inherited StructuralTypeConfiguration which could easily be checked in a Reflection query.

With CTP5 EntityTypeConfiguration<> (yes, renamed to that) now inherits StructuralTypeConfiguration<TEntityType>. So the Reflection method needs to be a little different.

When you tell your ModelBuilder to add configurations in CTP4 the Add() method accepted a StructuralTypeConfiguration instance.
In CTP5 the Add() method accepts a ComplexTypeConfiguration<TComplexType> or a EntityTypeConfiguration<TEntityType> this will give you a little headache. dynamic to the rescue!

First we search our assembly for EntityTypeConfigurations with Reflection (since this is the startup, don’t bother telling me about the Reflection performance)

//Culture is a class defined in the assembly where my Entity models reside
var typesToRegister = Assembly.GetAssembly(typeof(AnyOfYourConfigurationClassesHere)).GetTypes()
.Where(type => type.Namespace != null && type.Namespace.Equals(typeof(AnyOfYourConfigurationClassesHere).Namespace))
.Where(type => type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));

With each entry in this IEnumerable we call the ModelBinder.Configurations.Add() method, but we use dynamic since we don’t explicitly now the configuration type.

foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}

I think this is a perfect use of both the dynamic keyword aswell as still be able to automatically load the configurations used in your EF CodeFirst project.

December 8, 2010 Posted by | Development, Entity Framework | , | 21 Comments