Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load all Entity Framework 4.1 entity configuration entities via reflection?

In my OnModelCreating method for my data context I currently am manually mapping all my entity configuration mapping classes manually, like:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new UserMap());
    // 20 or so mapping configuration below
}

I want to streamline this by using reflection, so I have the following code:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Find all EntityTypeConfiguration classes in the assembly
        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            foreach (Type t in asm.GetTypes())
                if (t.IsDerivedFromOpenGenericType(typeof(EntityTypeConfiguration<>)))
                    modelBuilder.Configurations.Add(Activator.CreateInstance(t));   
    }

the IsDerivedFromOpenGenericType is from this question and works properly.

The problem is this doesn't compile because Activator.CreateInstance(t) returns an object, but the model builder is expecting a System.Data.Entity.ModelConfiguration.ComplexTypeConfiguration<TComplexType>.

Normally when using the Activator class I would just cast the object as whatever I expect type t to be (or what I expect the class to take), but since this is using a generics I don't know of a way to do that.

Does anyone have any ideas?

like image 334
KallDrexx Avatar asked Dec 04 '22 07:12

KallDrexx


1 Answers

I'm not sure why this information is so hard to find (at least it was for me), but there is a much simpler way to do it detailed here.

public class MyDbContext : DbContext
{
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Configurations.AddFromAssembly(Assembly.GetAssembly(GetType())); //Current Assembly
    base.OnModelCreating(modelBuilder);
  }
}
like image 137
im1dermike Avatar answered Dec 22 '22 00:12

im1dermike