Auto apply migrations fix
This commit is contained in:
@@ -103,26 +103,35 @@ var app = builder.Build();
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
|
||||
|
||||
db.Database.SetCommandTimeout(TimeSpan.FromMinutes(5));
|
||||
|
||||
try
|
||||
{
|
||||
var pending = await db.Database.GetPendingMigrationsAsync();
|
||||
if (pending.Any())
|
||||
{
|
||||
app.Logger.LogWarning("Applying {Count} pending migrations: {List}",
|
||||
pending.Count(), string.Join(", ", pending));
|
||||
await db.Database.MigrateAsync();
|
||||
app.Logger.LogInformation("Migrations applied successfully.");
|
||||
}
|
||||
else
|
||||
{
|
||||
app.Logger.LogInformation("No pending migrations.");
|
||||
}
|
||||
await db.Database.OpenConnectionAsync();
|
||||
|
||||
await db.Database.ExecuteSqlRawAsync(
|
||||
"EXEC sp_getapplock @Resource = N'DiunaBI_Migrations', @LockMode = 'Exclusive', @LockTimeout = 60000;");
|
||||
|
||||
logger.LogInformation("Ensuring database is up to date...");
|
||||
await db.Database.MigrateAsync();
|
||||
logger.LogInformation("Database is up to date.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
app.Logger.LogCritical(ex, "Migration failed - application will not start.");
|
||||
throw; // stop startup
|
||||
logger.LogCritical(ex, "Migration failed - application will not start.");
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
await db.Database.ExecuteSqlRawAsync(
|
||||
"EXEC sp_releaseapplock @Resource = N'DiunaBI_Migrations';");
|
||||
}
|
||||
catch { /* ignore */ }
|
||||
await db.Database.CloseConnectionAsync();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user