title: ASP.NET MVC 3 EF Code First - How do I make a model that optionally refers to a parent of its own type?
body: <p>I'm trying to create a model that can optionally refer to a parent of the same type, for example:</p>
  
  <pre><code>public class Category
  {
      public virtual long CategoryID { get; set; }
  
      public virtual Category? ParentCategory { get; set; }
  
      public virtual int UserID { get; set; }
      public virtual string Name { get; set; }
  
  }
  </code></pre>
  
  <p>As you can see there is an optional member called ParentCategory that is optional and refers to a class of type Category (i.e. the same type). As I'm sure you can guess, I'm trying to create a simple Category tree, where the root node(s) will not have a parent.</p>
  
  <p>This results in the following error when the Entity Framework tries to create the database:</p>
  
  <p><em>"The ForeignKeyAttribute on property 'ParentCategoryID' on type 'MyProject.Models.Category' is not valid. The navigation property 'Category' was not found on the dependent type 'MyProject.Models.Category'. The Name value should be a valid navigation property name."</em></p>
  
  <p>I also tried this:</p>
  
  <pre><code>public class Category
  {
      public virtual long CategoryID { get; set; }
  
      [ForeignKey("Category")]
      public virtual long? ParentCategoryID { get; set; }
  
      public virtual int UserID { get; set; }
      public virtual string Name { get; set; }
  
  }
  </code></pre>
  
  <p>But again this resulted in the same error.</p>
  
  <p>Is it possible to model this using EF Code First? Its easy to model it int he database if I were to create the database manually.</p>
  
  <p>Thanks in advance
  Ben</p>