We have something like this
var categories = _context.Categories.Include("Categories1.Categories1.Categories1");
That works and handles sub-categories up to 4-level deep (which is enough for now but who knows the future)
Is there a better way to do it?
More info
We use database-first. Category table has these columns:
Firstly, add data annotations and make properties readable
public partial class Category
{
public Category()
{
this.Children = new HashSet<Category>();
}
[Key]
public int Id { get; set; }
public string WhatEverProperties { get; set; }
public int ParentCategoryId { get; set; }
[ForeignKey("ParentCategoryId")]
[InverseProperty("Category")]
public Category Parent { get; set; } // name "Category1" as "Parent"
[InverseProperty("Category")]
public ICollection<Category> Children { get; set; } // Name it as Children
}
then, let's say we have got a category,
var category = context.Categories
.Include(x => x.Parent)
.Include(x => x.Children)
.FirstOrDefault(filter);
then we get its parents with:
var rootCategory = category.Parent?.Parent?.Parent; //up-to 4 levels by your request
by following extension, we can easily get its level:
///this extension works only if you used `.Include(x => x.Parent)` from query
public static class CategoryExtensions
{
public static int Level(this Category category)
{
if (category.Parent == null)
{
return 0;
}
return category.Parent.Level() + 1;
}
}