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가 외래키 속성을 갖게 된다.
'기타' 카테고리의 다른 글
| [ASP.NET Core/APOD] 댓글 기능 구현 (0) | 2023.04.08 |
|---|---|
| [ASP.NET Core/Devroup] 다른 엔터티(테이블)와 연관된 모델 속성에 데이터를 추가하고 저장하는 법 (0) | 2023.04.04 |
| [ASP.NET Core/Devroup] TempData, ViewData에 대한 고찰 (0) | 2023.03.28 |
| [ASP.NET Core/Devroup] HttpContext.Session을 _Layout에서 사용하기 위한 방법 (0) | 2023.03.26 |
| [ASP.NET Core/Devroup] await 키워드에 대해 (0) | 2023.03.26 |