NHibernate many-to-many mappings and order-by
Update: Frederico Tolomei has pointed out that this now works as you would expect if you place the order by on the many-to-many tag like this:
<bag name="SelectedOptions" cascade="none" lazy="false">
<key column="Answer" />
<many-to-many column="AnswerOption" class="AnswerOption" order-by="DisplayIndex asc"/>
</bag>
Just found this and it took me a while to figure out so posting here to remind myself as well as help anyone else who stumbles over the issue.
When you configure collection mappings in NHibernate, you can add an order-by attribute and specify the field to order the collection by as well as whether to sort ascending or descending.
With one-to-many mappings, the field you specify is a member of the entity contained in the collection so the following would contain a collection of Question instances sorted by DisplayIndex.
<bag name="Questions" cascade="all" order-by="DisplayIndex asc" lazy="false" fetch ="subselect">
<key column="QuestionnaireSection" />
<one-to-many class="Question" />
</bag>
However, if the mapping is a many-to-many, the order by clause is applied to the association table – the table in the middle of a many-to-many association mapped into a relational database. I cannot use the order-by attribute on the following collection mapping.
<bag name="SelectedOptions" cascade="none" lazy="false">
<key column="Answer" />
<many-to-many column="AnswerOption" class="AnswerOption" />
</bag>
The implementation of this may be erroneous (and could be argued as counter-intuitive), however as it stands the order-by clause of a collection mapped as a many-to-many is not overly useful as we cannot sort a collection of entities in the same manner as we can with a many-to-one mapping.
Hi, I just ran into this issue. Thanks for saving me the effort of doing further research into it.
Is it possible to use the order-by clause in a many-to-many mapping: put it inside the tag. NHibernate (2.1.2.400) will put the ORDER BY clause in right place in generated SQL.