Entity Framework Core란?
Entity Framework Core는 ORM(예: 개체 관계형 매퍼)입니다. 전 버전의 Entity Framework에 대한 경험이 있는 경우 익숙한 기능을 많이 찾을 수 있습니다.
EF Core는 가볍고 확장 가능한 오픈 소스 소프트웨어입니다. .NET Core와 마찬가지로 EF Core도 크로스 플랫폼입니다. Windows, Mac OS 및 Linux에서 작동합니다. EF core는 Microsoft의 공식 데이터 액세스 플랫폼입니다.
Entity Framework Core DbContext 클래스
Entity Framework Core에서 매우 중요한 클래스 중 하나는 DbContext 클래스입니다. 기본 데이터베이스와 상호 작용하기 위해 애플리케이션 코드에서 사용하는 클래스입니다. 데이터베이스 연결을 관리하고 데이터베이스에서 데이터를 검색하고 저장하는 데 사용되는 클래스입니다.
애플리케이션에서 DbContext 클래스를 사용하려면
- DbContext 클래스에서 파생되는 클래스를 만듭니다.
- DbContext 클래스는 Microsoft.EntityFrameworkCore 네임스페이스에 있습니다.
public class AppDbContext : DbContext
{ }
Entity Framework Core의 DbContextOptions
DbContext 클래스가 유용한 작업을 수행하려면 DbContextOptions 클래스의 인스턴스가 필요합니다.
DbContextOptions 인스턴스는 연결 문자열, 사용할 데이터베이스 공급자 등과 같은 구성 정보를 전달합니다 .
아래와 같이 base 키워드를 사용하여 DbContextOptions를 기본 DbContext 클래스 생성자 에 전달합니다 .
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
}
Entity Framework 핵심 DbSet
- DbContext 클래스에는 모델의 각 엔터티에 대한 DbSet<TEntity> 속성 이 포함 됩니다 .
- 현재 애플리케이션에는 Employee와 Department라는 2개의 엔터티 클래스가 있습니다.
- 따라서 AppDbContext 클래스에는 2개의 해당 DbSet 속성이 있습니다.
DbSet<Employee> DbSet<Department>
- 이러한 DbSet 속성을 사용하여 Employee 및 Department 클래스 의 인스턴스를 쿼리하고 저장합니다 .
- DbSet 속성에 대한 LINQ 쿼리는 기본 데이터베이스에 대한 쿼리로 변환됩니다.
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Employees { get; set; }
}
Seeding Data
OnModelCreating 메서드를 재정의하여 직원 및 부서 데이터를 시드합니다.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Code to seed data
}
AppDbContext 클래스 전체 코드
Models 폴더를 만들고 그 안에 다음 AppDbContext 클래스를 포함합니다.
using EmployeeManagement.Models;
using Microsoft.EntityFrameworkCore;
using System;
namespace EmployeeManagement.Api.Models
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//Seed Departments Table
modelBuilder.Entity<Department>().HasData(
new Department { DepartmentId = 1, DepartmentName = "IT" });
modelBuilder.Entity<Department>().HasData(
new Department { DepartmentId = 2, DepartmentName = "HR" });
modelBuilder.Entity<Department>().HasData(
new Department { DepartmentId = 3, DepartmentName = "Payroll" });
modelBuilder.Entity<Department>().HasData(
new Department { DepartmentId = 4, DepartmentName = "Admin" });
// Seed Employee Table
modelBuilder.Entity<Employee>().HasData(new Employee
{
EmployeeId = 1,
FirstName = "John",
LastName = "Hastings",
Email = "David@pragimtech.com",
DateOfBrith = new DateTime(1980, 10, 5),
Gender = Gender.Male,
DepartmentId = 1,
PhotoPath = "images/john.png"
});
modelBuilder.Entity<Employee>().HasData(new Employee
{
EmployeeId = 2,
FirstName = "Sam",
LastName = "Galloway",
Email = "Sam@pragimtech.com",
DateOfBrith = new DateTime(1981, 12, 22),
Gender = Gender.Male,
DepartmentId = 2,
PhotoPath = "images/sam.jpg"
});
modelBuilder.Entity<Employee>().HasData(new Employee
{
EmployeeId = 3,
FirstName = "Mary",
LastName = "Smith",
Email = "mary@pragimtech.com",
DateOfBrith = new DateTime(1979, 11, 11),
Gender = Gender.Female,
DepartmentId = 1,
PhotoPath = "images/mary.png"
});
modelBuilder.Entity<Employee>().HasData(new Employee
{
EmployeeId = 4,
FirstName = "Sara",
LastName = "Longway",
Email = "sara@pragimtech.com",
DateOfBrith = new DateTime(1982, 9, 23),
Gender = Gender.Female,
DepartmentId = 3,
PhotoPath = "images/sara.png"
});
}
}
}
필수 NuGet 패키지 설치
다음 2개의 NuGet 패키지를 설치합니다.
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
데이터베이스 연결 문자열
REST API 프로젝트의 appsettings.json 파일 에 다음 데이터베이스 연결 문자열을 포함합니다 .
"ConnectionStrings": {
"DBConnection": "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;Trusted_Connection=true"
}
API 프로젝트 시작 클래스의 ConfigureServices
appsettings.json 파일 에서 연결 문자열 읽기
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DBConnection")));
services.AddControllers();
}
데이터베이스 마이그레이션 생성 및 실행
다음 두 명령을 사용하여 초기 데이터베이스 마이그레이션을 만들고 실행합니다.
- Add-Migration InitialCreate
- Update-Database