Entity Framework does not know how to recursive queries. But the problem can be solved.
Option 1:
Make a view based on a recursive SQL query using WITH CTE . Then in the code to cause data retrieval from this twist.
Sample SQL code:
CREATE VIEW [dbo].[vw_Subcategories] AS WITH cte ( CategoryID, SubcatID) AS ( SELECT Id AS SubcatID, RootId as CategoryID FROM dbo.TableName UNION ALL SELECT e.Id AS SubcatID, cte.Id AS CategoryID FROM cte INNER JOIN dbo.TableName AS e ON e.RootId = cte.Id )
Option 2:
To make a simple separate recursive method in the code for getting child EF-objects:
List<Category> GoDownRecursive(int categoryId) { var res = new List<Category>(); foreach(var subcategory in DbContext.Cateogires.Where(c => c.RootId == categoryId) { res.Add(subcategory); res.AddRange(GoDownRecursive(subcategory.Id)); } return res; }
There will be more requests to the database, but if the nesting is small and the request is not the most frequent, then the option is acceptable. If desired, the resulting trees can be cached.