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

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

I have an Item. Item has a Category.

Category has ID, Name, Parent

相关标签:
15条回答
  • 2020-11-28 22:32

    You chould rather introduce a mapping table that maps each Category a parent and a child, instead of adding the parent and child property to the cargo itself.

    Depending on how often you need that information it can be queried on demand. Via unique constraints in the db you can avoid an infinite amount of relationships beeing possible.

    0 讨论(0)
  • 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<ItemInfo> items)
        {
            parent.Children = items.Where(a => a.ParentId == parent.Id).ToList();
            foreach (var child in parent.Children)
            {
                this.GetDecendantsFromList(child,items);
            }
        }
    
    0 讨论(0)
  • 2020-11-28 22:34

    My suggestion would be

    var query = CreateQuery()
        .Where(entity => entity.Id == Id)
        .Include(entity => entity.Parent);
    var result = await FindAsync(query);
    
    return result.FirstOrDefault();
    

    and it means it will load single entity and all this entity.Parent entities recursive.

    entity is same as entity.Parent
    
    0 讨论(0)
提交回复
热议问题