Chris Klingsater
Chris Klingsater

Reputation: 154

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; }
}

Upvotes: 1

Views: 1081

Answers (1)

ocuenca
ocuenca

Reputation: 39326

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);
}

Upvotes: 3

Related Questions