How to set navigation property in the same table in Entity Framework?

How to configure Entity Framework using a free configuration to behave the same as with attributes:

public class Product
{
    public int? ParentId { get; set; }
    [ForeignKey("ParentId")]
    public virtual Product Parent { get; set; }
}
0
source share
1 answer

Suppose you want to create a self-regulatory object, I assume that you have a class Product:

public class Product
{
    public int Id { get; set; }

    public int? ParentId { get; set; }

    public virtual Product Parent { get; set; }
}

In context, you need to implement a method OnModelCreatingto set up self-esteem.

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

All Articles