제니노트

Entity Framework 설치 + DB Context [C#] 본문

C#/C#

Entity Framework 설치 + DB Context [C#]

yangjennie 2023. 9. 25. 01:12
반응형

Entity Framework Core를 사용하여 DB 컨텍스트 클래스를 만들어주자 

 

ApplicationDbContext.cs 

using CoreProjectPrac.Models; //모델클래스 포함 
using Microsoft.EntityFrameworkCore; //관계형 db와 상호작용하는 라이브러리 

//Entity Framework Core를 사용하여 DB와 상호작용

namespace CoreProjectPrac.Data
{

    //데이터베이스의 연결 및 작업을 처리하는 주요한 클래스 
    public class ApplicationDbContext : DbContext //EntityFrameWork Core의 Dbcontext 클래스 상속 
    { 

      

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) //ctor 단축키 
        {
            //데이터 베이스 작업 수행할 수 있는 클래스 
        }

        public DbSet<Race> Races { get; set; } //Race DB 테이블 ,, Races 테이블은 Race모델과 연결 
        public DbSet<Club> Clubs { get; set; } //Club모델에 대한 DB 테이블 
        public DbSet<Address> Addresses { get; set; } //Address 모델에 대한 DB 테이블 
    }
}

 

Entity Frame Work 는 MS에서 개발한 ORM 프레임워크이다.

이 프레임워크는 개발자가 C#을 사용하여 관계형 DB와 상호작용하는 데 도움을 주는 도구와 라이브러리를 제공한다.

 

위 클래스는 객체 지향 코드와 관계형 DB의 중계자 역할을 하며, 

데이터베이스와 상호작용하고 데이터 모델을 표현하는 역할을 한다.

1. DB 연결 및 설정 

2. 데이터 모델과의 매핑 : 

각 클래스는 DB 테이블에 대응하여, 클래스의 속성은 테이블의 열에 매핑된다.

3. DB 작업 수행 (삽입, 업데이트,삭제 등)

4. DB 마이그레이션 : 이 클래스는 DB 스키마를 관리하고 업데이트 할 수 있다.

데이터 모델 변경 사항을 DB에 반영하거나 역으로 DB 스키마 코드 모델로 변환할 수 있다.

 

이를 통해 개발자는 DB에 직접 SQL 쿼리를 작성하지 않고도 데이터를 읽고 쓸 수 있다.

 

데이터베이스 마이그레이션이란

데이터베이스의 스키마(테이블,컬럼,제약 조건) 을 관리하는 과정이다.

예를 들어, 웹 애플리케이션을 개발 중인데

새로운 사용자 정보를 저장하기 위한 DB 테이블을 추가한다고 가정하자.

이때, DB 마이그레이션 도구를 사용하여 이 변경 사항을 쉽게 관리하고 업데이트 할 수 있다.

 

그 후 

Add-Migration InitialCreate

을 통해 스키마를 초기 상태로 설정하는 첫 번째 마이그레이션을 생성한다.

IntialCreate는 마이그레이션의 이름이다. 

새로운 마이그레이션을 만들 때마다 고유한 이름을 선택할 수 있다.

InitialCreate는 처음 DB를 만들 때 사용되며, 초기 데이터베이스 스키마를 정의하는 여할을 한다.

 

이 명령을 실행하면 EF Core는 현재 데이터모델과 이전 마이그레이션 상태를 비교하여

변경된 부분을 감지하고 이를 새로운 마이그레이션 클래스로 생성한다.

이후 데이터 모델이 변경 될 때마다 새로운 마이그레이션을 추가하여

데이터베이스 스키마를 업데이트 할 수 있다.

 

여기서 데이터 베이스 스키마란  

데이트 구조 자체다.

테이블,컬럼,기본키,외래키,제약 조건,인덱스를 다 포함하는게 스키마이다.

 

그 다음 초기 데이터를 채우기 위한 시드 데이터를 추가하는 클래스를 만들어주었다.

시드 데이터는 DB가 처음 생성되거나 재설정될 때 DB 초기 데이터를 삽입하는 데 사용된다.

 

using CoreProjectPrac.Data.Enum;
using CoreProjectPrac.Data;
using CoreProjectPrac.Models;
using Microsoft.AspNetCore.Identity;

namespace CoreProjectPrac.Data
{
    public class Seed
    {
        public static void SeedData(IApplicationBuilder applicationBuilder) //DB 초기화 및 시드 데이터 삽입 
        {
            using (var serviceScope = applicationBuilder.ApplicationServices.CreateScope()) //서비스 스코프 생성
                //의존성 주입을 사용하여 ApplicationDbContext와 같은 서비스를 가져온다.

            {
                //ApplicationDbcontext(DB 작업을 수행할 수 있는 Dbcontext)를 서비스 스코프를 통해 가져온다.
                var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();

                context.Database.EnsureCreated(); //DB 미 생성이라면 DB 생성 

                if (!context.Clubs.Any()) //Club 엔티티가 존재하는가? 
                {
                    context.Clubs.AddRange(new List<Club>() //초기 Club 데이터 추가 
                    {
                        new Club()
                        {
                            Title = "Running Club 1",
                            Image = "https://www.eatthis.com/wp-content/uploads/sites/4/2020/05/running.jpg?quality=82&strip=1&resize=640%2C360",
                            Description = "This is the description of the first cinema",
                            ClubCategory = ClubCategory.City,
                            Address = new Address()
                            {
                                Street = "123 Main St",
                                City = "Charlotte",
                                State = "NC"
                            }
                         },
                        new Club()
                        {
                            Title = "Running Club 2",
                            Image = "https://www.eatthis.com/wp-content/uploads/sites/4/2020/05/running.jpg?quality=82&strip=1&resize=640%2C360",
                            Description = "This is the description of the first cinema",
                            ClubCategory = ClubCategory.Endurance,
                            Address = new Address()
                            {
                                Street = "123 Main St",
                                City = "Charlotte",
                                State = "NC"
                            }
                        },
                        new Club()
                        {
                            Title = "Running Club 3",
                            Image = "https://www.eatthis.com/wp-content/uploads/sites/4/2020/05/running.jpg?quality=82&strip=1&resize=640%2C360",
                            Description = "This is the description of the first club",
                            ClubCategory = ClubCategory.Trail,
                            Address = new Address()
                            {
                                Street = "123 Main St",
                                City = "Charlotte",
                                State = "NC"
                            }
                        },
                        new Club()
                        {
                            Title = "Running Club 3",
                            Image = "https://www.eatthis.com/wp-content/uploads/sites/4/2020/05/running.jpg?quality=82&strip=1&resize=640%2C360",
                            Description = "This is the description of the first club",
                            ClubCategory = ClubCategory.City,
                            Address = new Address()
                            {
                                Street = "123 Main St",
                                City = "Michigan",
                                State = "NC"
                            }
                        }
                    });
                    context.SaveChanges();
                }
                //Races
                if (!context.Races.Any()) //Race 엔티티가 이미 존재하는가? 
                {
                    context.Races.AddRange(new List<Race>()
                    {
                        new Race()
                        {
                            Title = "Running Race 1",
                            Image = "https://www.eatthis.com/wp-content/uploads/sites/4/2020/05/running.jpg?quality=82&strip=1&resize=640%2C360",
                            Description = "This is the description of the first race",
                            RaceCategory = RaceCategory.Marathon,
                            Address = new Address()
                            {
                                Street = "123 Main St",
                                City = "Charlotte",
                                State = "NC"
                            }
                        },
                        new Race()
                        {
                            Title = "Running Race 2",
                            Image = "https://www.eatthis.com/wp-content/uploads/sites/4/2020/05/running.jpg?quality=82&strip=1&resize=640%2C360",
                            Description = "This is the description of the first race",
                            RaceCategory = RaceCategory.Ultra,
                            AddressId = 5,
                            Address = new Address()
                            {
                                Street = "123 Main St",
                                City = "Charlotte",
                                State = "NC"
                            }
                        }
                    });
                    context.SaveChanges();
                }
            }
        }

    
    }
}

 

 

각 Club 및 Race 데이터는 초기 데이터 베이스 테이블에 추가된다.

서비스 스코프는 ASP.NET COre 에서 의존성 주입 컨테이너를 사용하여

서비스 객체를 관리하고 스코프 내에서 서비스를 제공하거나 수명 주기를 관리하기 위한 개념이다.

서비스란 애플리케이션 내에서 필요한 기능 또는 객체이다.

예를 들어 DB연결,로깅,인증 등이다.

서비스 스코프란 서비스 객체의 활동범위이다.

각각의 서비스스코프는 서비스 객체를 생성하고 사용하는

일정한 영역을 가지며

그 내부 에서만 서비스 객체를 사용가능하다.

 

GetService<ApplicationDbContext>() 메서드를 사용해서 데이터베이스 컨텍스트 객체를 얻는다.

데이터베이스 컨텍스트는 데이터베이스와 상호작용하기 위한 핵심 객체로 이 스코프 내에서만 사용된다.

이 후 코드에서는 context를 사용하여 데이터베이스 작업을 수행한다.

초기데이터를 추가하거나 데이터르 조회하고 변경하는 작업이다.

이 작업들은 해당 서비스 스코프 내에서 수행되며 스코프가 종료될 때 context와 관련된 리소스가 자동으로 정리된다. 

 

 

그리고 program.cs 파일에

if (args.Length == 1 && args[0].ToLower() == "seeddata")
{
    //await Seed.SeedUsersAndRolesAsync(app);
    Seed.SeedData(app);

 

해당 코드를 삽입한다.

파워쉘에서 인수를 통해 seeddata라는 명령어를 확인하고

해당 명령어가 인식되면 DB 초기화 및 초기화 데이터 삽입 작업을 실행하는 부분 

args.Length == 1 && args[0].ToLower() == "seeddata" 

명령행 인수가 1개고 그 값이 seeddata인 경우 확인

args는 실행시 전달 된 명령행 인수를 뜻함

ToLower() 메서드를 사용하여 대소문자를 구별하지 않도록

Seed.SeedData() 로 데이터베이스 초기화 및 초기 데이터 삽입 작업을 수행

 

해주고 dotnet run seeddata 명령어로 

초기화해주면 된다.

 

 

반응형

'C# > C#' 카테고리의 다른 글

View [C#]  (0) 2023.09.25
Controller [C#]  (0) 2023.09.25
MVC 패턴 - 모델 [C#]  (0) 2023.09.24
ASP.net? ASP.net core? [C#]  (0) 2023.09.23
Class,Method,클래스 라이브러리 [C#]  (0) 2023.09.23
Comments