Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First. Children collection is null for parent

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

like image 301
lostaman Avatar asked Jul 26 '13 06:07

lostaman


People also ask

Is EF core code first?

EF Core Development ApproachesEF Core supports two development approaches 1) Code-First 2) Database-First. EF Core mainly targets the code-first approach and provides little support for the database-first approach because the visual designer or wizard for DB model is not supported as of EF Core 2.0.

What is EF Core 6?

EF Core 6.0 will allow temporal tables to be created via Migrations, as well as allowing access to the data through LINQ queries. This work is initially scoped as described on the issue. We may pull in additional support based on feedback during the release.


1 Answers

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);
like image 116
Sergey Berezovskiy Avatar answered Sep 22 '22 00:09

Sergey Berezovskiy