Hello guys,
I have two classes
Item and
Category with a many-to-many relationsship (an item may be part of many categories and a category may have several items). Thus, I have an intermediate table ITEM_CATEGORY which consists of 2 columns, ITEM_ID and CATEGORY_ID.
When I execute following ICriteria query and examine the generated SQL-code with the NHibernateProfiler, it shows up that NHibernate uses
two joins, one between the ITEM and ITEM_CATEGORY tables and the other between ITEM_CATEGORY and CATEGORY. However, only
one join would be necessary to do this query, since I only need the categoryID for my restriction, which is also available in the intermediate table (no other fields of the
Category class are used for the query).
Code:
Session.CreateCriteria<Item>()
.CreateCriteria("Categories", JoinType.InnerJoin)
.Add(Restrictions.IdEq(categoryId)))
.List<Question>());
Is there a possibility to tell NHibernate to use the CATEGORY_ID column in the intermediate table and saving the unnecessary second join?
I know this query also may be done more easily by using HQL, but the above code should just serve as a simple toy example to reveal the problem.
Best regards,
chrisscha