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

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

I have an Item. Item has a Category.

Category has ID, Name, Parent

15条回答
  •  -上瘾入骨i
    2020-11-28 22:10

    @parliament gave me an idea for EF6. Example for Category with Methods to load all parents up to root node and all children.

    NOTE: Use this only for non performance critical operation. Example with 1000 nodes performance from http://nosalan.blogspot.se/2012/09/hierarchical-data-and-entity-framework-4.html.

    Loading 1000 cat. with navigation properties took 15259 ms 
    Loading 1000 cat. with stored procedure took 169 ms
    

    Code:

    public class Category 
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public int? ParentId { get; set; }
    
        public virtual Category Parent { get; set; }
    
        public virtual ICollection Children { get; set; }
    
        private IList allParentsList = new List();
    
        public IEnumerable AllParents()
        {
            var parent = Parent;
            while (!(parent is null))
            {
                allParentsList.Add(parent);
                parent = parent.Parent;
            }
            return allParentsList;
        }
    
        public IEnumerable AllChildren()
        {
            yield return this;
            foreach (var child in Children)
            foreach (var granChild in child.AllChildren())
            {
                yield return granChild;
            }
        }   
    }
    

提交回复
热议问题