I have the following entity:
public class Entity {
Guid Id { get; set; }
Guid? ParentId { get; set; }
virtual Entity Parent { get; set; }
virtual ICollection<Entity> Children { get; set; }
}
Given a certain entity id: theId
, I wish to count the number of its children, its children's children, its children's children's children, etc..
One naive way to do it is as follows:
var count = dbContext.Where(x => x.Id == theId)
.SelectMany(x => x.Children)
.SelectMany(x => x.Children)
.SelectMany(x => x.Children)
.SelectMany(x => x.Children)
.SelectMany(x => x.Children)
.Count();
The problem is that I need to increase the number SelectMany
s to the max depth of children I have, which is not practical. I feel like this is not possible using EntityFramework and I have to use SQL procedures, but I wanted to ask just to make sure of this.
P.S. I'm using EF Core.