프로그래밍/.NET

Generic Host에서 EF Core MySql 사용하기

MAJG 2022. 12. 22. 22:39
반응형

EF Core 에서는 다양한 데이터베이스 공급자를 지원하고 있다.

이 글에서는 MySql과 MariaDB 모두를 지원하는 Pomelo.EntityFrameworkCore.MySql 를 사용한다.

 

 

1. NuGet 패키지 관리에서 Pomelo.EntityFrameworkCore.MySql를 검색하여 설치하거나 아래의 명령어를 입력한다.

dotnet add package Pomelo.EntityFrameworkCore.MySql

 

2. 아래의 코드를 복붙한다.

 

AppDbContext.cs

public class AppDbContext : DbContext {
    public AppDbContext() { }
}

Program.cs

static void Main(string[] args) => Host.CreateDefaultBuilder(args)

	// 생략
    
    .ConfigureServices((context, services) => {
        services.AddDbContext<AppDbContext>(
        dbContextOptions => dbContextOptions
            .UseMySql("Connection String", new MySqlServerVersion(new Version()))
            // The following three options help with debugging, but should
            // be changed or removed for production.
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging()
            .EnableDetailedErrors()
        );
    })
    .Build().Run();
}

 

프로젝트를 실행해 보면 아래와 같은 에러가 발생한다.

'AddDbContext' was called with configuration, but the context type 'AppDbContext' only declares a parameterless constructor. This means that the configuration passed to 'AddDbContext' will never be used. If configuration is passed to 'AddDbContext', then 'AppDbContext' should declare a constructor that accepts a DbContextOptions<AppDbContext> and must pass it to the base constructor for DbContext.

이 에러를 해결하려면 DbContext.cs 를 아래의 코드로 수정해야한다.

    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

Host를 설정할 때 넘겨줬던 dbContextOptions를 AppDbContext에서 받을 수 없었기 때문에 에러가 발생했던것이다.

반응형