Blog

EF Core + Postgres Migrations Playbook

Startup project/design paketleri, migration komutları, CI/CD güvenli güncelleme stratejisi ve yaygın tuzaklar.

8 dkMustafa Ulutaş

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:

AppDbContextFactory.cs
C#
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ı

migrations.sh
Shell
# 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.sql

CI/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.

Üretim veritabanında migration öncesi her zaman yedeğini alın.
Mustafa Ulutaş
Full-Stack Software Engineer

Modern web deneyimleri, üretimde çalışan backend sistemleri ve performans odaklı ürün tasarımı üzerinde çalışıyorum.