Reputation: 19
I'm currently building a web app with categories and multiple levels of sub-categories, think your average shopping website.
1. Category 1
1.1 Sub-Category
1.2 Sub-Category
1.2.1 Sub-Category
2. Category 2
2.1 Sub-Category
The category class is structured like this:
public class ProductType
{
public int ID { get; set; }
public string Name { get; set; }
public ProductType Parent { get; set; }
}
Each product then inherits the ProductType Class, and is referred by the ID. I'm building the search with PredicateBuilder and the problem is to recursively find all products within a category when doing a search.
My approach so far has been:
if (category != null && category.Length != 0)
{
foreach (string keyword in category)
{
int id = _context.ProductType.FirstOrDefaultAsync(p => p.Name == keyword).Result.ID;
predicate = predicate.Or(p => p.ProductType.Parent.ID == id);
predicate = predicate.Or(p => p.ProductType.ID == id);
}
}
If you search for Category 1 (from the example above) you of course only will get products in 1., 1.1 and 1.2. Products in sub-category 1.2.1 will not be included (not surprising).
How do you approach such problem? My guess is to do it recursively, passing the resulting ID's into the function and finding the next category of children having that parent ID. This is not possible with predicate builder (since your building a query, and not fetching the results...).
Upvotes: 2
Views: 1067