title: Self referencing / parent-child relationship in Entity Framework
body: <p>I read quite a number of posts of programmers that run into the <strong>Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values</strong> -exception when using a self-referencing relationship in Entity Framework.</p>
  
  <p>I am trying to get a parent-child relationship to work: </p>
  
  <pre><code>public class Category {
      public int CategoryId { get; set; }
      public string Name { get; set; }
      public int ParentId { get; set; }
      public Category Parent { get; set; }
      public List&lt;Category&gt; Children { get; set; }
  }
  </code></pre>
  
  <p>This is the configuration I use (Fluent API):</p>
  
  <pre><code>Property(c =&gt; c.ParentId).IsOptional();
  HasMany(c =&gt; c.Children).WithOptional(c =&gt; c.Parent).HasForeignKey(c =&gt; c.ParentId);
  //HasOptional(c =&gt; c.Parent).WithMany(c =&gt; c.Children).HasForeignKey(c =&gt; c.ParentId);
  </code></pre>
  
  <p>Both the HasMany() and HasOptional() configurations result in a  "Unable to determine a valid ordering for dependent operations..." exception when I try to save a new category like this:</p>
  
  <pre><code>context.Categories.Add(new Category { Name = "test" });
  </code></pre>
  
  <p>I don't understand why EF doesn't insert the Category with a null parentId. The database allows the ParentId foreign key to be null.</p>
  
  <p>Would you be able to tell me how to do this?</p>