title: Entity Framework 5 Code First Self-Referencing Relationship
body: <p>How would I map the following relationship in Entity Framework 5?</p>
  
  <pre><code>public class Item {
    public int Id { get; set; }
    public int? ParentItemId { get; set; }
    public string Value { get; set; }
  
    public Item ParentItem { get; set; }
    public List&lt;Item&gt; ChildItems { get; set; }
  }
  </code></pre>
  
  <p>I've tried this:</p>
  
  <pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder) {
    base.OnModelCreating(modelBuilder);
  
    modelBuilder.Entity&lt;Item&gt;()
                .HasOptional(i =&gt; i.ParentItem)
                .WithMany(i =&gt; i.ChildItems)
                .HasForeignKey(i =&gt; i.ParentItemId);
  }
  </code></pre>
  
  <p>and this:</p>
  
  <pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder) {
    base.OnModelCreating(modelBuilder);
  
    modelBuilder.Entity&lt;Item&gt;()
                .HasMany(i =&gt; i.ChildItems)
                .WithOptional(i =&gt; i.ParentItem)
                .HasForeignKey(i =&gt; i.ParentItemId);
  }
  </code></pre>
  
  <p>which both result in this error:</p>
  
  <p><strong>The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role.</strong></p>
  
  <p>If I start with database-first mapping, here is what the generated entity looks like:</p>
  
  <pre><code>public partial class Item
  {
      public Item()
      {
          this.ChildItems = new HashSet&lt;Item&gt;();
      }
  
      public int Id { get; set; }
      public Nullable&lt;int&gt; ParentItemId { get; set; }
      public string Value { get; set; }
  
      public virtual ICollection&lt;Item&gt; ChildItems { get; set; }
      public virtual Item ParentItem { get; set; }
  }
  </code></pre>
  
  <p>I know this will work if I start with db-first, I just need to know how to define the relationship in code-first.</p>