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
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:
@@ -23,8 +23,30 @@ public class ApplicationDbContextInitialiser
|
|||||||
{
|
{
|
||||||
if (_context.Database.IsSqlServer())
|
if (_context.Database.IsSqlServer())
|
||||||
{
|
{
|
||||||
|
// 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();
|
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)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -32,7 +54,6 @@ public class ApplicationDbContextInitialiser
|
|||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task SeedAsync()
|
public async Task SeedAsync()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|||||||
Reference in New Issue
Block a user