Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework One-Many Relationship on Same Entity

I need to define Organizational chart schema in Entity Framework.

PersonelJob Entity model is:

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 could be a job parent and have some job children.

How could map this entity to Database, with Fulent Api?

like image 356
H.Gh Avatar asked Jul 02 '26 08:07

H.Gh


1 Answers

Override the OnModelCreating method on your context and add this configuration:

modelBuilder.Entity<PersonelJob>()
            .HasOptional(pj => pj.Parent)
            .WithMany(pj=>pj.Childs)
            .HasForeignKey(pj => pj.ParentId);
like image 198
octavioccl Avatar answered Jul 04 '26 23:07

octavioccl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!