I have a problem with the Entity Framework Code First method for developing a tree hierarchy.
I need to save some tree in the database. My table has three fields: Id, Name and Parent_Id. In my solution, I created the following class:
public class TreeNode { public TreeNode() { Children = new List<TreeNode>(); } public int Id { get; set; } [Required] public String Name { get; set; } public virtual IList<TreeNode> Children { get; set; } public virtual TreeNode Parent { get; set; } }
I added the following configuration for the TreeNode class
modelBuilder.Entity<TreeNode>().HasOptional(c => c.Parent) .WithMany(c => c.Children) .Map(m => m.MapKey("Parent_Id"));
The problem is that children are always null when returning EF.
But if you get any child of a node, get its parent node through the Parent property, then the Child property will be populated correctly.
I am not sure what is wrong here. Look for recommendations.
Update: adding a virtual modifier to the navigation properties did not help
source share