Entity Framework model creating with reflection

c# ef-code-first entity-framework entity-framework-6 reflection

Question

I'm trying to create a model with classes derived in different assemblies. When I do this without reflection, evething is OK: migration is being created successfully and database is being updated.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<DerivedClass>();
}

When I use the reflection, migration is being created without any changes.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");

    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
    {
        var entityTypes = assembly
          .GetTypes()
          .Where(t =>
            t.BaseType == typeof(GameOperation));
        foreach (var type in entityTypes)
        {
            entityMethod.MakeGenericMethod(type)
                .Invoke(modelBuilder, new object[] { });
        }
    }
}

But when I'm launching application in debug mode, I see that entity adds to modelBuilder! And application says that

The model backing the 'EFDbContext' context has changed since the database was created

1
0
3/10/2017 5:50:48 PM

Accepted Answer

That's how it is supposed to be. What you're doing with reflection is a runtime thing. Who knows how many assemblies you have in the appdomain at runtime?

Scaffolding a migration with EF migrations is a design time thing. It can only work with what it sees at that specific point in time, when you actually scaffold the migration. A tool that runs at design time cannot take into consideration what will or will not happen at runtime.

If you configure your data model dynamically at runtime, I think the only way is to use your empty migration at also add reflection based code into that manually.

1
3/10/2017 5:58:14 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow