Let’s say we have an object model like this:
public class Category
{
public virtual Category Parent { get; set; }
public virtual string Name { get; set; }
public virtual ISet<Category> Children { get; protected set; }
}
public class Product
{
public virtual string Name { get; set; }
public virtual Category Category { get; set; }
public virtual decimal Price { get; set; }
}
On the database side, the relationship would be accomplished through a many-to-many relationship table, so the data schema would be something like this:
Category
=================
Id int PK
Name varchar(50)
Parent_Id int FK
Product
=================
Id int PK
Name varchar(50)
Price money
ProductToCategory
=================
Product_Id int PK
Category_Id int PK
Now let’s assume in the tree of categories is a branch that looks like this:
- Food
- Nut
- Cashew
- Peanut
- Pecan
- Bread
- Rye
- Wheat
- White
- Nut
Assuming we have products with potentially only one sub-category assigned, is it possible to construct a Criteria that would return all products with a category of Food with a single hit to the database and without using a CTE?
Or, given that there won’t be an abundance of categories, would it be better to load the full category map into memory and construct the criteria such that it searches for products where Category_Id in (...) and the list is constructed off the in-memory tree?
You’ll have to use a CTE to do this. I can’t think of a single SQL query that would load all products of a hierarchical category without using, let alone getting NHibernate to do it for you.
Yes. If there isn’t much data and this is an option, it’s the simplest, fastest, low-maintenance, least complex way of doing it.