0

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();
    }
user7235699
  • 431
  • 2
  • 13
  • https://stackoverflow.com/questions/19648166/nice-universal-way-to-convert-list-of-items-to-tree – StepUp Feb 21 '19 at 09:30
  • If you mean if it is recursive you should try to flatten your table and build you tree after – StepUp Feb 21 '19 at 09:52

0 Answers0