ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • EF Core - (부록) Project Setup
    .NET/Database 2025. 2. 3. 22:59

     

     

    해당 작업을 위해서 두가지 프로젝트를 생성하였는데,

    Repository 프로젝트는 DbContext를 직접사용하여 Database에 여러가지 명령을 보내는 역할을 하는 클래스들을 넣을 프로젝트 입니다. 클래스 라이브러리 프로젝트를 생성하시면 됩니다.

    Application 프로젝트는 여러 DI처리와 콘솔 입력에 대한 처리를 할 프로젝트인데, 콘솔 어플리케이션 프로젝트로 생성하시면 됩니다.

     

    보통 Database와 연결하는 어플리케이션의 역할은 웹 백엔드가 하는 것이 일반적 이지만, 꼭 웹이 아니더라도 위와같이 구성하여 연결 할 수 있습니다. 

    어떤 프로젝트라 하더라도 리포지토리의 내용이 변하지 않는다는 점과, 더 간략한 실행을 보여주기 위해서 적합한 방법으로 콘솔 어플리케이션으로 구성했습니다.

     

     

    Repository 프로젝트는 Database 프로젝트를 참조하고 다음 코드를 ProductRepository에 추가 합니다. 

    using Database.Context;
    using Database.Entity;
    
    namespace ClassLibrary1;
    
    public class ProductRepository
    {
        private readonly ShopDbContext _context;
    
        public ProductRepository(ShopDbContext context)
        {
            _context = context;
        }
        
        public List<Product> GetProducts()
        {
            return _context.Products.ToList();
        }  
    }

    Application 프로젝트는 Repository 프로젝트를 참조합니다. (Database 프로젝트는 Repository가 가지고 있기 때문에 자동 참조됩니다.)

    패키지는 Microsoft.Extensions.Hosting을 다운받아 참조합니다. 

    Migrator에서 사용한 appsettings.json을 복사해서 Application 프로젝트에 옮겨줍니다. 

    Program.cs에 다음 코드를 작성합니다. 

    using Repository;
    using Database.Context;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    
    using IHost host = Host.CreateDefaultBuilder(args)
        .ConfigureServices((context, services) =>
        {
            var cons = context.Configuration.GetConnectionString("DefaultConnection");
            services.AddTransient<ProductRepository>(); // 의존성 등록
            services.AddDbContextPool<ShopDbContext>(x => x.UseNpgsql(cons));
        })
        
        .Build();
    
    var service = host.Services.GetRequiredService<ProductRepository>();
    var products = service.GetProducts();
    foreach (var product in products)
    {
        Console.WriteLine(product.ProductName);
    }
    
    Console.ReadLine();

     

    Program.cs에서 위와같이 제네릭 호스트를 사용해서 Repository와 DbContext를 주입하고 Connection String을 연결해 줍니다.

     

    실행해보면 다음과 같이 쿼리가 조회되어야 합니다.

     

    추후 생산성을 위한 EF Core 시리즈에서도 위와같은 방식으로 테스트를 진행할 예정입니다. 

    위 내용은 아래 git repository에서 확인 할 수 있습니다.

    atawLee/ProductivityImprovementEFCoreORM at fa0f9ccffbb06761d414d874d9535617ce6e4706

    '.NET > Database' 카테고리의 다른 글

    EF Core 테이블 상속 매핑(TPC)  (0) 2025.03.10
    EF Core 테이블 상속 매핑 (TPT)  (0) 2025.02.17
    EF Core - Code First  (0) 2025.01.11
    EF Core - Domain 분리구조 만들기  (0) 2024.03.22
    EF Core 시작하기(2) - DI,CRUD  (0) 2023.12.22
Designed by Tistory.