So I have a simple table that looks like this to represent a tree of categories and subcategories supporting a dynamic N levels of depth.
CategoryID int NOT NULL (PK)
ParentCategoryID int NULLABLE (FK to self)
CategoryName varchar(100) NOT NULL
My entity (typed this out from memory, sorry if there's a silly mistake in here):
public class Category
{
public int CategoryId { get; set; }
public int ParentCategoryId { get; set; }
public string CategoryName { get; set; }
public virtual Category ParentCategory { get; set; }
public IDbSet<Category> ImmediateChildCategories { get; set; }
}
Using an execution-deferred lambda expression in Entity Framework (6.x) in C# (4.5+), how would I identify all categories that are descendants of a specified category?
My pseudocode SQL query that I'd like would be this:
SELECT * FROM Category WHERE AnyLevelOfAncestorId = 123;
My pseudocode EF query that I'd like to see would be this (paging is there to emphasize my need for execution-deferred support):
_db.Categories.Where(cat => cat.HasAncestor(123)).Skip(1000).Take(25).ToList();
Additional details:
- A category with a NULL ParentCategoryID is a root node of a tree (there can be several).
- No category will have its own CategoryID nor any descendant's ID as a ParentCategoryID (i.e. no circular relationships and all relationships eventually terminate at a root node although I may query for an ID lower than a root node)
- I'm not sure if I want to include the specified ID (123) in the results or not. So I'll accept an answer that goes either way and adjust as necessary once I know if I want that specific one also included.