Search code examples
c#entity-frameworkef-code-firstnavigation-propertiesef-fluent-api

How do I configure a navigation property to the same table in Entity Framework?


How do I configure Entity Framework using fluent configuration to behave the same way that I would do this with attributes:

public class Product
{
    public int? ParentId { get; set; }
    [ForeignKey("ParentId")]
    public virtual Product Parent { get; set; }
}

Solution

  • Supposing that you want to create a self referencing entity, I assume that you have a Product class like this:

    public class Product
    {
        public int Id { get; set; }
    
        public int? ParentId { get; set; }
    
        public virtual Product Parent { get; set; }
    }
    

    In the context, you need to implement the OnModelCreating method in order to configure the self reference.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      modelBuilder.Entity<Product>().
           HasOptional(e => e.Parent).
           WithMany().
           HasForeignKey(m => m.ParentId);
    }