본문 바로가기

Programming/Database

Entity framework core 사용하여 기본키(PK) 지정, 복합키(Composite Key) 지정 하는방법. Data annotation and Fluent API

반응형

Entity Framework(이하 EF)는 닷넷용 ORM이다.

 

EF Core는 EF6를 다시 작성한 버전이다. 둘의 차이점이 궁금하다면 링크

 

Entity Framework 6와 Entity Framework Core 비교

Entity Framework 6와 Entity Framework Core 중에 선택하는 방법을 제공합니다.

docs.microsoft.com

 

Entity class를 작성하면 기본적으로 "Id" 혹은 <type name> Id가 PK로 지정된다.

아래 예시의 경우 "Id", "StudentId" 프로퍼티가 PK로 지정된다.

Public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
}

 

명시적으로 특정 프로퍼티를 PK로 지정하고 싶다면 크게 두 가지 방법이 있다.

첫 번째는 Data Annotation을 사용하는 것, 두 번째는 Fluent API를 사용하는 것이다.

 

Data Annotation 방법은 아래와같이 [Key]라는 attribute를 사용해 PK를 지정해주면 된다.

Public class Student
{
    [Key]
    public string Name { get; set; }
    public string Age { get; set; }
}

 

Fluent API를 이용한 방법은 EFCore에서 제공하는 DbContext class를 상속받아

OnModelCreating을 구현해주어야 한다.

아래와 같이 EntityClass에서 HasKey를 이용해 PK를 설정한다.

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>()
                .HasKey(d => new { d.Name });
        }

 

그렇다면 복합키(Composite Key)는 어떻게 지정할까?

Data Annotation 사용하면 간단히 [Key] attribute를 복수개 사용하면 될 것 같지만 아쉽게도 EFCore는 지원하지 않는다. 

(EF6에선 가능하다)

ref: https://www.entityframeworktutorial.net/code-first/key-dataannotations-attribute-in-code-first.aspx

 

Data Annotations: Key Attribute in EF 6 & EF Core

Data Annotations - Key Attribute in EF 6 & EF Core The Key attribute can be applied to a property in an entity class to make it a key property and the corresponding column to a PrimaryKey column in the database. The default convention creates a primary key

www.entityframeworktutorial.net

 

EFCore에서 복합키를 지정하려면 Fluent API를 사용해야한다. 

사용법은 간단하다 HasKey 설정을 원하는 모든 프로퍼티들을 넣어주면 된다.

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>()
                .HasKey(d => new { d.Name, d.Age });
        }

 

 

 

반응형