fix: Improve database migration strategy - only migrate if needed
All checks were successful
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 2m16s

- Check if database exists before creating
- Only apply pending migrations
- Skip migration if database is up to date
- Prevents 'file already exists' error on restart
This commit is contained in:
masoud
2025-12-07 21:16:49 +00:00
parent 70a06933a9
commit 7ec9c4077c

View File

@@ -23,7 +23,29 @@ public class ApplicationDbContextInitialiser
{
if (_context.Database.IsSqlServer())
{
await _context.Database.MigrateAsync();
// Check if database already exists and has pending migrations
bool dbExists = await _context.Database.CanConnectAsync();
if (dbExists)
{
_logger.LogInformation("Database exists, checking for pending migrations...");
var pendingMigrations = await _context.Database.GetPendingMigrationsAsync();
if (pendingMigrations.Any())
{
_logger.LogInformation("Applying {Count} pending migrations", pendingMigrations.Count());
await _context.Database.MigrateAsync();
}
else
{
_logger.LogInformation("Database is up to date, no migrations needed");
}
}
else
{
_logger.LogInformation("Database does not exist, creating and migrating...");
await _context.Database.MigrateAsync();
}
}
}
catch (Exception ex)
@@ -32,7 +54,6 @@ public class ApplicationDbContextInitialiser
throw;
}
}
public async Task SeedAsync()
{
try