Database

[EF Core] 마이그레이션 명령 정리, 자주 나는 오류 해결

전자기린 2026. 11. 10. 00:39

EF Core 마이그레이션에서 실제로 쓰는 명령과, 자주 나는 오류 대응을 정리했습니다.

절차

  1. 도구 설치
  2. 마이그레이션 추가·적용
  3. 운영 반영 방식
  4. 자주 나는 오류

 

1. 도구 설치

dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design

설치 후 dotnet ef --version이 안 되면 ~/.dotnet/tools가 PATH에 있는지 확인합니다.

2. 마이그레이션 추가와 적용

dotnet ef migrations add InitialCreate
dotnet ef database update

프로젝트가 여러 개면 데이터 프로젝트와 시작 프로젝트를 지정합니다.

dotnet ef migrations add AddOrderTable -p ./Data -s ./Web

3. 운영 반영

운영에서는 database update를 직접 돌리기보다 SQL 스크립트를 뽑아 검토한 뒤 적용하는 편이 안전합니다.

dotnet ef migrations script -o migrate.sql --idempotent

4. 자주 나는 오류

No migrations were applied. The database is already up to date.

연결 문자열이 다른 DB를 보거나, 이미 적용된 상태입니다. 이력은 dotnet ef migrations list로 확인합니다.

The model backing the context has changed — 모델만 바꾸고 마이그레이션을 만들지 않았습니다. migrations add 후 database update.

Unable to create a 'DbContext' of type ... — 디자인 타임에 컨텍스트를 만들지 못할 때 납니다. 아래 팩터리를 추가합니다.

public class DesignTimeFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public AppDbContext CreateDbContext(string[] args)
    {
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseSqlServer("Server=localhost;Database=App;Trusted_Connection=True;")
            .Options;
        return new AppDbContext(options);
    }
}

데이터 손실 경고(SQL Server) — 컬럼 삭제나 형 변환이 있으면 경고가 나옵니다. -- --force로 넘기기 전에 스크립트로 실제 SQL을 확인하세요.

정리

  1. 추가는 migrations add, 적용은 database update
  2. 운영은 migrations script --idempotent로 뽑아 검토 후 적용
  3. 이력은 migrations list로 확인