Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to map ordered list in nhibernate?

I have two classes: container which contains dynamic ordered list of Element.

What C# collection should I use?

What DB schema would you suggest me?

How should I configure the nhibernate mapping?

TIA

like image 571
Elad Benda Avatar asked Nov 24 '11 21:11

Elad Benda


1 Answers

NHibernate supports collections implemented by System.Collections.SortedList and Iesi.Collections.SortedSet. You must specify a comparer in the mapping file:

<set name="Aliases" table="person_aliases" sort="natural">
    <key column="person"/>
    <element column="name" type="String"/>
</set>

<map name="Holidays" sort="My.Custom.HolidayComparer, MyAssembly" lazy="true">
    <key column="year_id"/>
    <index column="hol_name" type="String"/>
    <element column="hol_date" type="Date"/>
</map>

Allowed values of the sort attribute are unsorted, natural and the name of a class implementing System.Collections.IComparer.

If you want the database itself to order the collection elements use the order-by attribute of set, bag or map mappings. This performs the ordering in the SQL query, not in memory.

Setting the order-by attribute tells NHibernate to use ListDictionary or ListSet class internally for dictionaries and sets, maintaining the order of the elements. Note that lookup operations on these collections are very slow if they contain more than a few elements.

<set name="Aliases" table="person_aliases" order-by="name asc">
    <key column="person"/>
    <element column="name" type="String"/>
</set>

<map name="Holidays" order-by="hol_date, hol_name" lazy="true">
    <key column="year_id"/>
    <index column="hol_name" type="String"/>
    <element column="hol_date type="Date"/>
</map>

Note that the value of the order-by attribute is an SQL ordering, not a HQL ordering!

Associations may even be sorted by some arbitrary criteria at runtime using a Filter().

sortedUsers = s.Filter( group.Users, "order by this.Name" );

Source: NHibernate and Sorted Collections

like image 84
Gerard Avatar answered Oct 04 '22 07:10

Gerard