EF Core migration yönetimi, Clean Architecture projelerinde başlangıçta kafa karıştırıcı olabilir. Startup ve infrastructure projeleri ayrı olduğunda hangi komutları kullanmanız gerektiğini bu yazıda netleştiriyorum.
IDesignTimeDbContextFactory
Infrastructure projesinde DbContext tanımlı, ama appsettings.json Api projesinde. EF Core araçlarının çalışması için bu fabrikayı oluşturun:
public class AppDbContextFactory
: IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../Api"))
.AddJsonFile("appsettings.Development.json")
.Build();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseNpgsql(config.GetConnectionString("Default"))
.Options;
return new AppDbContext(options);
}
}CLI Komutları
# Migration ekle
dotnet ef migrations add <İsim> \
--project src/Infrastructure \
--startup-project src/Api \
--output-dir Persistence/Migrations
# Veritabanını güncelle
dotnet ef database update \
--project src/Infrastructure \
--startup-project src/Api
# Son migration'ı geri al (henüz apply edilmediyse)
dotnet ef migrations remove \
--project src/Infrastructure \
--startup-project src/Api
# SQL script üret (CI/CD için)
dotnet ef migrations script \
--project src/Infrastructure \
--startup-project src/Api \
--idempotent \
-o migration.sqlCI/CD Stratejisi
Üretimde dotnet ef database update yerine idempotent SQL script kullanın. Bu şekilde migration geçmişi olmadan da çalışır ve daha güvenlidir.