Fix 'Invalid object name Provinces' error - reset migrations and switch to Migrate()

This commit is contained in:
2026-06-09 02:13:29 +03:30
parent 7a4190ca13
commit 569e39b58d
7 changed files with 740 additions and 174 deletions

View File

@@ -123,6 +123,7 @@ builder.Services.AddDbContext<ComplexDBContext>(
);
*/
builder.Services.AddApiVersioning(Options =>
{
Options.AssumeDefaultVersionWhenUnspecified = true;
@@ -177,13 +178,39 @@ builder.Services.AddSwaggerGen(c =>
var app = builder.Build();
// Ensure database is created and apply pending migrations
// Apply pending migrations and create database if not exists
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ComplexDBContext>();
// EnsureCreated creates all tables from the model if they don't exist,
// while Migrate applies any pending migrations on top.
dbContext.Database.EnsureCreated();
// If the database was previously created with EnsureCreated() (no __EFMigrationsHistory),
// seed the history table so Migrate() knows the initial state
if (!dbContext.Database.GetAppliedMigrations().Any())
{
try
{
// Check if any tables exist (meaning EnsureCreated was used before)
var tableCount = dbContext.Database.ExecuteSqlRaw(
"SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'");
if (tableCount > 0)
{
// Create __EFMigrationsHistory if it doesn't exist and seed it
dbContext.Database.ExecuteSqlRaw(
"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '__EFMigrationsHistory') " +
"BEGIN " +
"CREATE TABLE [__EFMigrationsHistory] ([MigrationId] nvarchar(150) NOT NULL, [ProductVersion] nvarchar(32) NOT NULL, PRIMARY KEY ([MigrationId])); " +
"END " +
"IF NOT EXISTS (SELECT * FROM __EFMigrationsHistory WHERE MigrationId = '20260608224155_InitialCreate') " +
"INSERT INTO __EFMigrationsHistory (MigrationId, ProductVersion) VALUES ('20260608224155_InitialCreate', '6.0.3')");
}
}
catch
{
// Database doesn't exist yet, Migrate() will create it
}
}
dbContext.Database.Migrate();
// Seed essential reference data and test data
await DataSeeder.SeedAsync(dbContext);
}