본문 바로가기
기타

[ASP.NET Core/Devroup] ForeignKey: 외래키에 대해

by 항붕쿤 2023. 3. 31.
using System.ComponentModel.DataAnnotations.Schema;

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
        
    //Foreign key for Standard
    public int StandardId { get; set; }
    public Standard Standard { get; set; }
}

public class Standard
{
    public int StandardId { get; set; }
    public string StandardName { get; set; }
    
    public ICollection<Student> Students { get; set; }
}

 

위 예시는 외래키를 정의하는 일반적인 코드이다.
Standard 클래스에는 StandardId라는 속성이 존재하고 마찬가지로 Student 클래스에도 StandardId라는 속성이 존재다. Student 클래스에 Standard 클래스의 PK속성에 해당하는 이름을 가진 속성이 존재하고 그 밑에 Standard 타입의 Standard 속성이 존재함으로써 StandardId는 외래키 속성이 된다.
public Standard Standard { get; set; }는 navigation property로 StandardId가 Standard 클래스의 외래키이고 1:N 관계임을 표시한다
public ICollection<Student> Students { get; set; }Standard 클래스의 navigation property로 Standard 클래스와 Student 클래스가 1:N 관계임을 표현한다. 이 속성을 통해 Standard 객체와 해당 객체와 연결된 모든 Student 객체를 쉽게 가져올 수 있다. 그러나 외래키를 만드는데 있어 꼭 필요하진 않다.(없어도 된다.)

using System.ComponentModel.DataAnnotations.Schema;

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
        
    [ForeignKey("Standard")]
    public int StandardRefId { get; set; }
    public Standard Standard { get; set; }
}

public class Standard
{
    public int StandardId { get; set; }
    public string StandardName { get; set; }
    
    public ICollection<Student> Students { get; set; }
}

만약 위와 같이 외래키가 될 속성의 이름이 부모 클래스 PK 속성의 이름과 일치하지 않을 경우 외래키기 될 속성의 위에 ForeignKey 속성을 적고 그 파라미터에 부모 클래스의 이름을 적으면 StandardRefId가 외래키 속성을 갖게 된다.

using System.ComponentModel.DataAnnotations.Schema;

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
        
    public int StandardRefId { get; set; }
    
    [ForeignKey("StandardRefId")]
    public Standard Standard { get; set; }
}

public class Standard
{
    public int StandardId { get; set; }
    public string StandardName { get; set; }
    
    public ICollection<Student> Students { get; set; }
}

위와 같이 navigation property 위에 외래키가 될 속성의 이름을 ForeignKey속성의 파라미터에 넣어도 StandardRefId가 외래키 속성을 갖게 된다.