EF Code First. Collection of children for parents

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

+6
source share
1 answer

Or mark properties as virtual , as @Cuong suggested. This will ensure lazy loading (every time you try to access the "Children", a server request will be executed):

 public virtual IList<TreeNode> Children { get; set; } 

OR load children when loading a parent:

 var nodes = context.TreeNodes.Include(n => n.Children); 
+7
source

Source: https://habr.com/ru/post/950327/


All Articles