简体   繁体   中英

Run EF migrations on Startup in asp.net core 6 application

How can I run ef migrations on startup in asp.net 6 application.

This is my 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());

How can I execute MyContext.Database.Migrate() here?

Try below:

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();

Just add following lines in Program.cs

await using var scope = app.Services.CreateAsyncScope();
using var db = scope.ServiceProvider.GetService<DataContext>();
await db.Database.MigrateAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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