title: Entity Framework: Dependencies due to foreign key constraints
body: <p>I have been looking around for a solution and cannot find good information. A lot of EF documentation is very out of date. Here is my problem.</p>
  
  <p>If I add a child to a parent via the ParentID navigation property, everything works fine.</p>
  
  <p>If I add a child to a parent via the Children list and the child is pre-existing, I get this exception:</p>
  
  <blockquote>
    <p>DbUpdateException: Unable to determine
    a valid ordering for dependent
    operations. Dependencies may exist due
    to foreign key constraints, model
    requirements, or store-generated
    values.</p>
  </blockquote>
  
  <p>If I add a child to a parent via the Children list and the child is new (also needs to be persisted), I get this exception:</p>
  
  <blockquote>
    <p>DbUpdateConcurrencyException: Store
    update, insert, or delete statement
    affected an unexpected number of rows
    (0). Entities may have been modified
    or deleted since entities were loaded.
    Refresh ObjectStateManager entries.</p>
  </blockquote>
  
  <p>Node.cs</p>
  
  <pre><code>public class Node
  {
    public long ID { get; private set; }
    public long? ParentID { get; set; }
    public List&lt;Node&gt; Children { get; set; }
  }
  </code></pre>
  
  <p>Relevant DbContext.cs</p>
  
  <pre><code>protected override void OnModelCreating(DbModelBuilder mb)
  {
    mb.Entity&lt;Node&gt;()
      .HasMany(c =&gt; c.Children)
      .WithOptional()
      .HasForeignKey(c =&gt; c.ParentID);
  }
  </code></pre>