ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [EF Core] 여러 프로젝트가 참조된 솔루션에서 dotnet ef 명령어 사용시 유의사항정리
    .NET/개념 및 유용한 팁 2021. 8. 31. 22:22
    반응형

    CleanArchitecture까진 필요없고, 단일 프로젝트 형식은 테스트 케이스 개발에 불편함이 있어 별도 프로젝트 템플릿을 구현하고 있다. 구현하면서 Entity Framework Core를 이용해 Code First 방식으로 DB를 마이그레이션 하는 방법을 다루게 되었는데 뻘짓을 많이 하여 리스트로 정리할겸 포스트를 쓴다.

    1. 시작프로젝트에 Microsoft.EntityFrameworkCore.Tools Nuget 패키지가 설치되어 있어야 한다.

    설치가 안되어있을 경우, 아래와 같은 오류가 나온다.

    Your startup project 'Template.WebApi' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.

     

    2. DbContext 구현체가 있는 프로젝트와 Injection 코드가 서로 다른 참조이면, AddDbContext의 Use 옵션설정에 migration assembly 도 정의해야 한다.

    DbContext가 선언된 프로젝트(ex : Template.Application)와 실제 Db연결정보 및 UseSqlServer()와 같이 정확하게 특정 DB제품을 사용하도록 구현된 프로젝트(ex : Template.Infrastructure)가 다르게 위치해 있다면 MigrationsAssembly에 DB제품을 사용하도록 구현된 프로젝트(ex : Template.Infrastructure)명이 정의되어 있어야 한다.

    Your target project 'Template.Infrastructure' doesn't match your migrations assembly 'Template.Application'. Either change your target project or change your migrations assembly.Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("Template.Infrastructure")).

     

    [잘못된 예]

    public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration config)
    {
        services.AddDbContext<SchoolDbContext>(
            options => options.UseSqlServer(config.GetConnectionString(nameof(SchoolDbContext)))
        );
        return services;
    }

     

    [수정된 예]

    public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration config)
    {
        services.AddDbContext<SchoolDbContext>(
            options => options.UseSqlServer(config.GetConnectionString(nameof(SchoolDbContext)),
            builder => builder.MigrationsAssembly("Template.Infrastructure")) // 추가코드
        );
        return services;
    }

     

    3. ef 명령어 사용시 Injection 코드가 선언된 프로젝트(ex : Template.Infrastructure)와 시작프로젝트(ex : Template.WebApi)가 다르면,  --project, --startup-project 옵션으로 구분줘야 한다.

    [명령어 예시]

    dotnet ef migrations add init --project .\Template.Infrastructure\ --startup-project .\Template.WebApi\

     

     

    반응형

    댓글

Designed by Tistory.