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()) {