Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 614
Aishwarya Avatar asked Dec 06 '25 10:12

Aishwarya


2 Answers

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();
like image 87
SBI Avatar answered Dec 08 '25 00:12

SBI


Just add following lines in Program.cs

await using var scope = app.Services.CreateAsyncScope();
await using var db = scope.ServiceProvider.GetService<DataContext>();
await db.Database.MigrateAsync();
like image 38
ˈvɔlə Avatar answered Dec 07 '25 22:12

ˈvɔlə



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!