I'm rewriting a simple application that uses Asp.NET 5. but now I'm using Asp.NET 6 for the new version of my app. Quick question: what's the replacement of database auto migration (like below in .NET5) in .NET6 or What approach should I use for automatic migration after application launch in .NET6?
Sample in .NET5:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, PgSqlDbContext context)
{
context.Database.Migrate();
/*
other middlewares
*/
}
.NET6 :
var app = builder.Build();
// ???? for auto migration
// other middlewares
CodePudding user response:
Here's my translation from Microsoft's Docs on 5 to 6 migration to your use case:
var app = builder.Build();
var context = app.Services.GetRequiredService<PgSqlDbContext>();
context.Database.Migrate();
I did not test this, so fingers crossed!
CodePudding user response:
I have tried to add this code and the project works successfully.
var app = builder.Build();
using (var serviceScope = app.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
var dbcontext = services.GetRequiredService<PgSqlDbContext>();
var conn = dbcontext.Database.GetConnectionString();
}
//other middlewares
