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
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With