fix: Use EnsureCreatedAsync instead of MigrateAsync for initial db setup
All checks were successful
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 2m9s
All checks were successful
Build and Deploy to Kubernetes / build-and-deploy (push) Successful in 2m9s
- EnsureCreatedAsync creates db only if it doesn't exist - Returns false if db already exists (idempotent) - Prevents 'CMS.mdf already exists' error - Still applies pending migrations when needed
This commit is contained in:
@@ -23,28 +23,24 @@ public class ApplicationDbContextInitialiser
|
||||
{
|
||||
if (_context.Database.IsSqlServer())
|
||||
{
|
||||
// Check if database already exists and has pending migrations
|
||||
bool dbExists = await _context.Database.CanConnectAsync();
|
||||
// Use EnsureCreated for initial setup, then apply migrations
|
||||
// EnsureCreated is idempotent - safe to call multiple times
|
||||
var created = await _context.Database.EnsureCreatedAsync();
|
||||
|
||||
if (dbExists)
|
||||
if (!created)
|
||||
{
|
||||
_logger.LogInformation("Database exists, checking for pending migrations...");
|
||||
var pendingMigrations = await _context.Database.GetPendingMigrationsAsync();
|
||||
|
||||
if (pendingMigrations.Any())
|
||||
// Database exists, check for pending migrations
|
||||
_logger.LogInformation("Database already exists, checking for migrations...");
|
||||
var pending = await _context.Database.GetPendingMigrationsAsync();
|
||||
if (pending.Any())
|
||||
{
|
||||
_logger.LogInformation("Applying {Count} pending migrations", pendingMigrations.Count());
|
||||
_logger.LogInformation("Applying {Count} pending migrations", pending.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();
|
||||
_logger.LogInformation("Database created successfully");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user