Self-Referencing Parent-Child relationschip with EntityFramework 6

PUBLISHED ON 15 DEC 2018 — ENTITY FRAMEWORK

Self-Referencing Parent-Child relationschip with EntityFramework 6

Good Articles

Self referencing Table

When facing a parent child relation in a table, where an item can have (optional) a parent item and can also have (optional) many childrens.

Example:

public class Processs 
{
    public int Id {get; private set;}
    public int? ParentProcessId {get; private set;}
    public Process ParentProcess {get; set;}
    public ICollection<Process> ChildrensProcesses {get; private set;}
}

protected override OnModelBuilder(ModelBuilder modelBuilder)
{
	modelBuilder.Entity<Vorgang>()
        .HasOptional(x=>x.ParentProcess)
        .WithMany(x=>x.ChildrensProcesses)
        .HasForeignKey(x=>x.ParentProcessId);    
}
comments powered by Disqus