Sorting related collection in Nhibernate query
This is partly due to this .
I would like to find a way to sort the associated (HasMany) result of a collection directly in a Nhibernate query.
ICriteria criteria = Session.CreateCriteria(typeof(PortalPage));
criteria.CreateAlias("PartialViews", "vc");
criteria.AddOrder(Order.Asc("vc.ColumnNumber"));
criteria.Add(Property.ForName("Url").Eq(pageUrl));
return criteria.UniqueResult<PortalPage>();
Generates selection correctly using ORDER BY, but the result in the associated collection is not ordered.
I would like to avoid sorting the collection after returning the result (for example using linq for objects)?
UPDATE: As Steve suggested the problem could be solved by hardcoding the order attribute in the mapping, like so:
HasMany(x => x.PartialViews).KeyColumnNames.Add("PageId").AsBag().SetAttribute("order-by", "ColumnNumber");
source to share
Did you specify the collection as a list type and not a bag or a set? If you make sure to use the list display type and specify the index column to display the list, everything should be taken care of for you.
See the docs here and there for more details here , although this second post is an older post, so stay tuned for anything that may have changed.
Here's an example of a simple mapping of a collection of lists:
<list name="Images table="Images">
<key column="Id"/>
<index column="Position"/>
<element type="String" column="FileName"/>
</list>
A loose match for this example would be something like this:
HasMany(x => x.Images).AsList(x => x.WithColumn("Position"));
source to share