I have two tables: Category Table
public class Category
{
public int Id {get; set;}
public string Title { get; set; }
public int? ParentCategoryId { get; set; }
[ForeignKey("ParentCategoryId")]
public Category ParentCategory { get; set; }
}
and Post Table:
public class Post
{
public int Id {get; set;}
public string Title { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public Category Category { get; set; }
}
I can have arbitrary level of nesting in Category Table. For example Vehicles -> Bikes -> Sports Bikes ...
How can I search posts by category and load all posts related to that category or any level of nested child category? Currently my code works for only a fixed level of nestedness.
Following is the code in PostRepository File
public async Task<IEnumerable<Post>> List(PostFilter postFilter)
{
var query = _dbContext.Post.AsQueryable();
if (postFilter.SearchCategoryId > 0){
query = query.Where(p => p.Category == postFilter.SearchCategoryId);
query = query.Where(p => p.Category.ParentCategoryId == postFilter.SearchCategoryId);
}
return await query.Include(p => p.Category).ToListAsync();
}