From 5441e280e0bec1932cc1a5462cd93f1ced68f843 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Zieli=C5=84ski?= Date: Sat, 18 Oct 2025 10:04:47 +0200 Subject: [PATCH] Auto apply EF migrations on startup --- BimAI.API/Program.cs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/BimAI.API/Program.cs b/BimAI.API/Program.cs index a5ad58a..b3c729f 100644 --- a/BimAI.API/Program.cs +++ b/BimAI.API/Program.cs @@ -83,6 +83,33 @@ builder.Services.AddCors(options => var app = builder.Build(); +// Auto-apply migrations on startup +using (var scope = app.Services.CreateScope()) +{ + var db = scope.ServiceProvider.GetRequiredService(); + + 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."); + } + } + catch (Exception ex) + { + app.Logger.LogCritical(ex, "Migration failed - application will not start."); + throw; // stop startup + } +} + if (app.Environment.IsDevelopment()) { app.UseSwagger();