title: Effective way of saving parent-child tables in MVC Entity Framework
body: <p>I am trying out MVC with Entity Framework and I am trying to understand the best ways to use EF.</p>
  
  <p>I have a page where student’s info together with the father/mother info can be saved. My current code works, as shown below, but I feel like I am not doing this correctly. Is there a better way for me to do this? Do I need to call SaveChanges() twice? </p>
  
  <p>The db is structured as follows;
  <strong>Person</strong>
  PersonID INT PK
  FirstName Varchar(50)</p>
  
  <p><strong>Student</strong>
  Student_PersonID INT FK
  Father_PersonID  INT FK
  Mother_PersonID  INT FK</p>
  
  <p>The student, father and mother are all FK to the person table.</p>
  
  <p>The registration view page has textboxes for the 3 persons:</p>
  
  <pre><code>@Html.EditorFor(s =&gt; s.Person.FirstName)    @*student name*@
  @Html.EditorFor(f =&gt; f.Father.FirstName)    @*father name*@
  @Html.EditorFor(f =&gt; f.Mother.FirstName)    @*mother name*@
  </code></pre>
  
  <p>The controller code looks like this</p>
  
  <pre><code>[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();
      }
  }
  </code></pre>
  
  <p>I am using VS2010, MVC 3, and this was modeled after the database first concept.</p>