简体   繁体   English

使用反射创建实体框架模型

[英]Entity Framework model creating with reflection

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! 但是,当我以调试模式启动应用程序时,我看到该实体添加到了ModelBuilder中! And application says that 应用程序说

The model backing the 'EFDbContext' context has changed since the database was created 自创建数据库以来,支持“ EFDbContext”上下文的模型已更改

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? 谁知道在运行时您在appdomain中有多少个程序集?

Scaffolding a migration with EF migrations is a design time thing. 用EF迁移来支持迁移是设计时的事情。 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. 如果您在运行时动态配置数据模型,我认为唯一的方法是使用空迁移,同时还要在其中手动添加基于反射的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM