Database migrations are now checked in production.
This commit is contained in:
@@ -79,6 +79,45 @@ builder.Services.AddCascadingAuthenticationState();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Check and apply database migrations
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var services = scope.ServiceProvider;
|
||||
var logger = services.GetRequiredService<ILogger<Program>>();
|
||||
|
||||
try
|
||||
{
|
||||
var context = services.GetRequiredService<AppDbContext>();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
// Auto-apply migrations in development
|
||||
logger.LogInformation("Applying database migrations (Development)...");
|
||||
await context.Database.MigrateAsync();
|
||||
logger.LogInformation("Database migrations applied successfully");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Check if migrations are needed in production
|
||||
var pendingMigrations = await context.Database.GetPendingMigrationsAsync();
|
||||
if (pendingMigrations.Any())
|
||||
{
|
||||
logger.LogError(
|
||||
"Database has pending migrations: {Migrations}",
|
||||
string.Join(", ", pendingMigrations));
|
||||
throw new InvalidOperationException(
|
||||
"Database migrations are pending. Run migrations before starting the application.");
|
||||
}
|
||||
logger.LogInformation("Database is up to date");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "An error occurred while checking database migrations");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user