EF Code First. Children collection is null for parent

ef-code-first entity-framework

Question

I have a problem with Entity Framework Code First approach in developing tree hierarchies.

I need to store some tree in a database. My table has three fields Id, Name and Parent_Id. I created the following class in my solution:

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've added the following configuration for TreeNode class

            modelBuilder.Entity<TreeNode>().HasOptional(c => c.Parent)
                    .WithMany(c => c.Children)
                    .Map(m => m.MapKey("Parent_Id"));

The issue is that Children is always null when returned by EF.

But if retrieve some child node, get its Parent node via Parent property then Children property is filled correctly.

I'm not sure what's wrong here. Looking for your advise.

Update: addition of virtual modifier to navigation properties didn't help

1
8
7/26/2013 6:36:41 AM

Accepted Answer

Either mark properties as virtual, as @Cuong suggested. This will enable lazy-loading (each time when you will try to access Children additional query to server will be executed) :

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

OR eager load children when loading parent:

var nodes = context.TreeNodes.Include(n => n.Children);
11
7/26/2013 6:29:49 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow