在 asp.net core 6 应用程序的启动时运行 EF 迁移

问题描述 投票:0回答:2

如何在 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() ?

c# entity-framework asp.net-core entity-framework-migrations
2个回答
35
投票

尝试以下:

var app = builder.Build();

// omitted

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

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

// omitted

app.Run();

8
投票

只需在 Program.cs 中添加以下行

await using var scope = app.Services.CreateAsyncScope();
await using var db = scope.ServiceProvider.GetService<DataContext>();
await db.Database.MigrateAsync();
© www.soinside.com 2019 - 2024. All rights reserved.