【问题标题】:Run EF migrations on Startup in asp.net core 6 application在 asp.net core 6 应用程序的启动时运行 EF 迁移
【发布时间】:2021-12-31 12:23:19
【问题描述】:

如何在 asp.net 6 应用程序中启动时运行 ef 迁移。

这是我的 Program.cs

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
var serverVersion = new MySqlServerVersion(new Version(8, 0, 23));
builder.Services.AddDbContext<MyContext>(x => x.UseMySql(connectionString, serverVersion)
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging()
            .EnableDetailedErrors());

如何在此处执行 MyContext.Database.Migrate()?

【问题讨论】:

  • 请记住,您可能不想每次都运行迁移,例如,如果您的代码在多实例基础上运行(用于负载共享等),因为多个实例会尝试更新同时数据库。
  • @Neil 我明白了,我现在只在一个 vps 上运行

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


【解决方案1】:

试试下面:

using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    var context = services.GetRequiredService<MyContext>();    
    context.Database.Migrate();
}

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 2021-10-02
    • 2018-12-23
    • 1970-01-01
    • 2021-12-29
    • 2022-01-15
    • 2020-10-02
    • 2020-08-20
    • 2017-07-26
    相关资源
    最近更新 更多