Entity Framework One-way relationship to the same entity

I need to define an org chart in Entity Framework.

PersonelJob Entity Model:

public class PersonelJob : BaseEntity
{
    public Int64 ID { get; set; }
    public string Name { get; set; }
    public Int64? ParentId { get; set; }
    public virtual PersonelJob Parent { get; set; }
    public virtual ICollection<PersonelJob> Childs { get; set; }
}

      

As you can see, each job can be a parent of the job and have some working children.

How can I map this object to a database with the Fulent Api?

+3


source to share


1 answer


Override the method OnModelCreating

in your context and add this configuration:



modelBuilder.Entity<PersonelJob>()
            .HasOptional(pj => pj.Parent)
            .WithMany(pj=>pj.Childs)
            .HasForeignKey(pj => pj.ParentId);

      

+1


source







All Articles