Does Entity Framework support some kind of recursive LINQ or do I have to write my queries in SQL? (Using ParentId - Typical category subcategory problem)
1 Answer
I think you can solve it by using Include
method inside extension method to get only piece of hierarchy or get it all. Even it can generate pretty ugly SQL.
using(var context = new HierarchyContext())
{
var depth = context
.Categories
.IncludeHierarchy(3, nameof(Category.Children));
var root = depth.Single(c => c.Id == 2);
}
public static IQueryable<T> IncludeHierarchy<T>(this IQueryable<T> source,
uint depth, string propertyName)
where T : Category
{
var temp = source;
for (var i = 1; i <= depth; i++)
{
var sb = new StringBuilder();
for (var j = 0; j < i; j++)
{
if (j > 0)
{
sb.Append(".");
}
sb.Append(propertyName);
}
var path = sb.ToString();
temp = temp.Include(path);
}
var result = temp;
return result;
}
public class Category
{
// Primary key
public int Id { get; set; }
// Category name
public string Name { get; set; }
// Foreign key relationship to parent category
public int ParentId { get; set; }
// Navigation property to parent category
public virtual Category Parent { get; set; }
// Navigation property to child categories
public virtual ICollection<Category> Children { get; set; }
}
Queryable
and expression tree limitation in general - no way to define recursive expression. (2) Taking the whole hierarchy is possible due the EF navigation property fixup. But taking a part of the tree with all children is not possible with single L2E query (except if you load the whole three and then apply the filter on memory). See Is recursive query possible in LINQFinc<..>
inside. I meant pure expressions (which are requirement in queryables because they have to be recognizable and translatable, which cannot be said for unknownFunc<...>
code)