How does Entity Framework work with recursive hierarchies? Include() seems not to work with it

前端 未结 15 1802
再見小時候
再見小時候 2020-11-28 21:53

I have an Item. Item has a Category.

Category has ID, Name, Parent

15条回答
  •  星月不相逢
    2020-11-28 22:33

    And now for a completely different approach to hierarchical data, for example populating a treeview.

    First, do a flat query for all data, and then build the object graph in memory:

      var items = this.DbContext.Items.Where(i=> i.EntityStatusId == entityStatusId).Select(a=> new ItemInfo() { 
                Id = a.Id,
                ParentId = a.ParentId,
                Name = a.Name,
                ItemTypeId = a.ItemTypeId
                }).ToList();
    

    Get the root item:

     parent = items.FirstOrDefault(a => a.ItemTypeId == (int)Enums.ItemTypes.Root);
    

    Now build your graph:

     this.GetDecendantsFromList(parent, items);
    
    
     private void GetDecendantsFromList(ItemInfo parent, List items)
        {
            parent.Children = items.Where(a => a.ParentId == parent.Id).ToList();
            foreach (var child in parent.Children)
            {
                this.GetDecendantsFromList(child,items);
            }
        }
    

提交回复
热议问题