【问题标题】:Create and Apply Migration at run time in .Net Core - Entity Framework Core在 .Net Core - Entity Framework Core 中运行时创建和应用迁移
【发布时间】:2021-01-21 12:17:06
【问题描述】:

是否有任何可能的方法来创建迁移并在运行时在 dot net core 中应用。 我遇到过 context.database.migrate() 如果存在迁移文件,它会创建/更新数据库。 满足从终端运行 add-migration 的需要。

有没有办法实现这种添加迁移,然后从代码以编程方式运行 migrate()

提前致谢

【问题讨论】:

标签: c# asp.net-core entity-framework-core programmatically


【解决方案1】:

首先你需要添加类:

public class InitMigrations
{
    private readonly SDMContext context;
    public InitMigrations(SDMContext context)
    {
        this.context = context;
    }
    public void MigrateDatabase()
    {
        context.Database.Migrate();
    }
}

然后添加Startup.cs注入这个服务

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var initMigrations = serviceScope.ServiceProvider.GetRequiredService<InitMigrations>();
    initMigrations.MigrateDatabase();
}

【讨论】:

  • 如果存在迁移脚本,这将进行迁移。我想在运行时生成迁移脚本
猜你喜欢
  • 1970-01-01
  • 2017-04-26
  • 2020-06-06
  • 2019-02-12
  • 2017-10-27
  • 2016-08-21
  • 2017-07-03
  • 2015-05-20
  • 2020-11-18
相关资源
最近更新 更多