EF LINQ include nested entities [duplicate]

元气小坏坏 提交于 2021-02-11 12:03:28

问题


I have multi-leveled entities with the following hierarchy: Parent-> RootChildren -> Children -> Children -> .....

Class Parent 
{
   public int Id {get; set;}
   public virtual Child RootChildren {get; set;}
}    
Class Child
{
   public virtual List<Child> Children {get; set;}
}

Now, I want to include entity which include all the child as nested way.

I tried the following but it didn't work:

var parents = dbContext.Parent 
                    .Where(p => p.Id == id)
                    .Select(r => r.RootChildren)
                    .Include(c => c.Children)
                    .ToList();

It gives me result for first children but does not include all the nested children present in the tree.

Any piece of advise or information would be highly appreciated. Thanks!


回答1:


You shouldn't try to apply Include after Select and perform Include hierarchical;

var parents = dbContext.Parent
    .Where(p => p.Id == id)
    .Include(c => c.RootChildren.Children)
    .Select(r => r.RootChildren)
    .ToList();


来源:https://stackoverflow.com/questions/48096194/ef-linq-include-nested-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!