title: Using EF 4.1 Inserting a parent record and multiple child records as a single "Unit of Work"
body: <p>I am practicing with a code-first set of classes with a parent-child relationship between them.  </p>
  
  <pre><code>public class Parent
  {
      public int Id ( get; set; }
      public string Name { get; set; }
      public List&lt;Child&gt; Children { get; set; }
  
      public Parent()
      {
          Children = new List&lt;Child&gt;();
      }
  }
  
  public class Child()
  {
      public int Id ( get; set; }
      public string Name { get; set; }
  }
  
  public class MyContext : DbContext
  {
      public DbSet&lt;Parent&gt; Parents { get; set; }
      public DbSet&lt;Child&gt; Children { get; set; }
  }
  </code></pre>
  
  <p>In a simple console app I create a parent and create two child records and add them to the parent.  If I then call the SaveChanges() only the first child is added to the children table.</p>
  
  <pre><code>var x = new MyContext();
  
  var c1 = new Child { Name = "Alpha-Child" };
  var c2 = new Child { Name = "Beta-Child" };
  
  var p = new Parent {Name = "Alpha-Parent"};
  
  p.Children.Add(c1);
  p.Children.Add(c2);
  
  x.Parents.Add(p);
  
  x.SaveChanges();
  </code></pre>
  
  <p>Well that was not what I wanted, so I tried to maybe add then to both the parent object and the context object.</p>
  
  <pre><code>var x = new MyContext();
  
  var c1 = new Child { Name = "Alpha-Child" };
  var c2 = new Child { Name = "Beta-Child" };
  
  var p = new Parent {Name = "Alpha-Parent"};
  
  p.Children.Add(c1);
  p.Children.Add(c2);
  
  x.Children.Add(c1);
  x.Children.Add(c2);
  
  x.Parents.Add(p);
  
  x.SaveChanges();
  </code></pre>
  
  <p>That got both the child records into the database, but only one of them (the first) was associated with the parent record.</p>
  
  <p>Last, but not least, I tried to do a call to SaveChanges() after each call to Parent.Add().</p>
  
  <pre><code>var x = new MyContext();
  
  var c1 = new Child { Name = "Alpha-Child" };
  var c2 = new Child { Name = "Beta-Child" };
  
  var p = new Parent {Name = "Alpha-Parent"};
  
  x.Parents.Add(p);
  
  p.Children.Add(c1);
  x.SaveChanges();
  
  p.Children.Add(c2);
  x.SaveChanges();
  </code></pre>
  
  <p>But, this breaks my idea of how the "Unit of Work" Pattern works.  I "Should be able to call SaveChanges() once, and have all my changes take place, correct?</p>
  
  <p>So, what am I doing wrong?</p>