MVC를 Entity Framework와 함께 사용하려고하고 있으며 EF를 사용하는 최선의 방법을 이해하려고합니다.MVC Entity Framework에서 부모 - 자식 테이블을 저장하는 효과적인 방법
나는 학생의 정보가 아버지/어머니 정보와 함께 저장 될 수있는 페이지가 있습니다. 아래에 나와있는 것처럼 현재 코드가 작동하지만 제대로 수행하지 못하는 것 같습니다. 이 일을하는 더 좋은 방법이 있습니까? SaveChanges()를 두 번 호출해야합니까?
db는 다음과 같이 구성됩니다. 사람 테이블에 사람 PersonID INT PK FIRSTNAME VARCHAR (50)
학생 Student_PersonID INT FK Father_PersonID INT FK Mother_PersonID INT FK
학생, 아버지와 어머니 모두 FK .
등록보기 페이지는 3 명 텍스트 상자가 있습니다
@Html.EditorFor(s => s.Person.FirstName) @*student name*@
@Html.EditorFor(f => f.Father.FirstName) @*father name*@
@Html.EditorFor(f => f.Mother.FirstName) @*mother name*@
컨트롤러 코드는 내가 VS2010를 사용하고이
[HttpPost]
public ActionResult Register(Student sm)
{
using (var db = new SMEntities())
{
db.People.Add(sm.Person);
db.People.Add(sm.Mother);
db.People.Add(sm.Father);
db.SaveChanges(); //save the 3 persons
int studentId = sm.Person.PersonID;
int motherId = sm.Mother.PersonID;
int FatherId = sm.Father.PersonID;
Student s = new Student();
s.Student_PersonID = studentId;
s.Father_PersonID = FatherId;
s.Mother_PersonID = motherId;
db.Students.Add(s);
db.SaveChanges();
}
}
, MVC 3과 같은,이 데이터베이스를 모델로했다 첫 번째 개념.