From bd04483bed444b53c14d45a103095690f93de8ad Mon Sep 17 00:00:00 2001 From: James Kolpack Date: Wed, 3 Dec 2025 15:20:43 -0500 Subject: [PATCH] Database migrations are now checked in production. --- WebApp/Program.cs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/WebApp/Program.cs b/WebApp/Program.cs index 976ae7c..9dcea3c 100644 --- a/WebApp/Program.cs +++ b/WebApp/Program.cs @@ -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>(); + + try + { + var context = services.GetRequiredService(); + + 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()) {