'Control a reference in entity framework?

enter image description hereControl a reference in entity framework

Open question .Net Core 5 - Entities.

What do you think is the most efficient way to work in MVC mode, having 1 single entity that references itself. example

 public class ClassGroupAndSubgroup
 {
    
     public int ID { get; set; }

    public int SubGroupId { get; set; }

    public string Name{ get; set; }

}

ClassGroupAndSubgroup principalGroup { SubGroupId = 0, Name ="Principal"}; ----> Id = 1 (AutoNum)
ClassGroupAndSubgroup SubGroup { SubGroupId = 1, Name ="Item_1_Subgroup1"}; ----> Id = 2 (AutoNum)
ClassGroupAndSubgroup SubGroup_Two { SubGroupId = 1, Name ="Item_2_Subgroup1"}; ----> Id = 3 (AutoNum)
ClassGroupAndSubgroup principalGroup { SubGroupId = 3, Name ="Item_1_Subgroup2"};----> Id = 4 (AutoNum)

What I want is to make reference on itself, but from EntityFramework Core. I did it a long time ago with algorithms in C# and SQL but I can't do it in entity



Solution 1:[1]

You want the Foreign Key property to refer to the parent, not the child, eg

 public class Foo
 {
    
    public int ID { get; set; }

    public int ParentFooId{ get; set; }

    public Foo Parent {get;set;}

    public string Name{ get; set; }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1