title: Code First Mapping for Entity Framework Hierarchy
body: <p>I have a model that looks like this:</p>
  
  <pre><code>public class Category
  {
      public string Id { get; set; }
      public string Description { get; set; }
      public Category Parent { get; set; }
      public ICollection&lt;Category&gt; Children { get; set; }
      public ICollection&lt;Product&gt; Products { get; set; }
  }
  </code></pre>
  
  <p>With a database table that looks like</p>
  
  <pre><code>Categories
      Id (PK varchar(5))
      Description (nvarchar(50))
      ParentId (FK varchar(5))
  </code></pre>
  
  <p>But Im stumped when it comes to setting up the mapping</p>
  
  <pre><code>modelBuilder.Entity&lt;Category&gt;()
      .HasMany(x =&gt; x.Children)
      .WithMany(x =&gt; x.Children)
      .Map(m =&gt;
          {
              m.ToTable("Categories");
              m.MapLeftKey(x =&gt; x.Id, "Id");
              m.MapRightKey(x =&gt; x.Id, "ParentId");
          });
  </code></pre>
  
  <p>I can see why the mapping fails (StackOverflowException), but am unsure as to how to fix it.  Any help would be greately appreciated.</p>
  
  <p>This is using the latest release of EF (4.1?).</p>
  
  <p>Thanks!</p>