간단히 말해서 외래 키를 사용하면 하루를 절약 할 수 있습니다.
학교 법인과 도시 법인 이 있다고 가정 하고 이것은 도시에 많은 학교가 있고 학교가 도시에 속하는 다 대일 관계입니다. 그리고 도시가 이미 조회 테이블에 존재하므로 새 학교를 삽입 할 때 도시가 다시 삽입되는 것을 원하지 않습니다.
처음에는 다음과 같이 엔티티를 정의 할 수 있습니다.
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
public class School
{
public int Id { get; set; }
public string Name { get; set; }
[Required]
public City City { get; set; }
}
그리고 다음 과 같이 School 삽입을 수행 할 수 있습니다 (이미 newItem에 City 속성이 할당되어 있다고 가정 ).
public School Insert(School newItem)
{
using (var context = new DatabaseContext())
{
context.Set<School>().Add(newItem);
// use the following statement so that City won't be inserted
context.Entry(newItem.City).State = EntityState.Unchanged;
context.SaveChanges();
return newItem;
}
}
위의 접근 방식은이 경우 완벽하게 작동 할 수 있지만, 더 명확하고 유연한 외래 키 접근 방식을 선호합니다 . 아래 업데이트 된 솔루션을 참조하십시오.
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
public class School
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("City_Id")]
public City City { get; set; }
[Required]
public int City_Id { get; set; }
}
이러한 방식으로 학교 에 외래 키 City_Id 가 있고 City 엔티티를 참조하도록 명시 적으로 정의합니다 . 따라서 School 삽입과 관련하여 다음을 수행 할 수 있습니다.
public School Insert(School newItem, int cityId)
{
if(cityId <= 0)
{
throw new Exception("City ID no provided");
}
newItem.City = null;
newItem.City_Id = cityId;
using (var context = new DatabaseContext())
{
context.Set<School>().Add(newItem);
context.SaveChanges();
return newItem;
}
}
이 경우 새 레코드 의 City_Id 를 명시 적으로 지정하고 그래프 에서 City 를 제거하여 EF가 School 과 함께 컨텍스트에 추가하지 않도록합니다 .
첫인상에서는 외래 키 접근 방식이 더 복잡해 보이지만 다 대다 관계를 삽입 할 때이 사고 방식을 사용하면 많은 시간을 절약 할 수 있습니다 (학교와 학생 관계, 학생 City 속성이 있음) 등등.
이것이 당신에게 도움이되기를 바랍니다.