title: One to many recursive relationship with Code First
body: <p>I am trying to implement a simple self referencing relationship with EF 6.1.2 Code First.</p>
  
  <pre><code>public class Branch 
  {
      [Key]
      public int Id { get; set; }
  
      [Required]
      public string Name { get; set; }
  
      public int? ParentId { get; set; }
  
      [ForeignKey("ParentId")]
      public virtual Branch Parent { get; set; }
  
      public ICollection&lt;Branch&gt; Children { get; set; } // direct successors
  }
  </code></pre>
  
  <p>In my application I have exactly one root branch. And except for this single root branch, every branch has exactly one parent (the parentId of the root branch is NULL). Other than that, every branch can have [0..n] subbranches.</p>
  
  <p>I have two issues:</p>
  
  <ol>
  <li>Do I need to specify any extra FluentApi code in  OnModelCreating(DbModelBuilder modelBuilder) in order to make EF understand this one-to-many self-referencing relationship? I tried this: <code>modelBuilder.Entity&lt;Branch&gt;().HasOptional&lt;Branch&gt;(b =&gt; b.Parent).WithMany(b =&gt; b.Children).HasForeignKey(b =&gt; b.ParentId);</code> But I am not sure if I need this at all.</li>
  <li>For a given branch I want to retrieve all children (all the way down the hierarchy). This is what I came up with so far:</li>
  </ol>
  
  <p>.</p>
  
  <pre><code> public IEnumerable&lt;Branch&gt; GetBranches(Branch anyBranch)
   {
       return anyBranch.Flatten(b =&gt; b.Children);
   }
  </code></pre>
  
  <p>and</p>
  
  <pre><code> public static IEnumerable&lt;T&gt; Flatten&lt;T&gt;(this T node, Func&lt;T, IEnumerable&lt;T&gt;&gt; selector)
   {
       return selector(node).SelectMany(x =&gt; Flatten(x, selector))
                              .Concat(new[] { node });
   }
  </code></pre>
  
  <p>The second snippet is not from me. I found it somewhere else on StackOverflow. To be honest, I hardly understand how it is supposed to work. </p>
  
  <p>When I run my application and call GetBranches() (I tried this with several different branches), I receive an exception inside the Flatten() method. The error message says: "Value cannot be null.
  Parameter name: source". Unfortunately this does not give me any clue what is going wrong here. </p>
  
  <p>I hope anybody can help me out here? Thanks so much!</p>