tags:

views:

52

answers:

1

I'm trying to work out the best method (i.e. most simple and foolproof) for mapping a many-to-many collection that should be sorted when it is retrieved.

Here is the basic entity and table:

public class Person
{
    private IList<AddressHistoryRecord> _addressHistory = new List<AddressHistoryRecord>();

    IList<AddressHistoryRecord> AddressHistory
    {
        get { return _addressHistory; }
        set { return _addressHistory; }
    }
}

public class AddressHistoryRecord
{
    public Guid Id { get; set; }
    public Guid AtAddressSince { get; set; }
    ...
}

Tables are:

table t_Person { ... }
table t_PersonAddressHistory { PersonId, AddressHistoryRecordId }
table t_AddressHistoryRecord { Id, AtAddressSince ... }

So I want to be able to have the Person's address history retrieved in sorted order based on the child AddressHistoryRecord table's AtAddressSince column. What's my best option?

+1  A: 

I tend to use "idbag" for my many-to-many mappings but the example below will work with a normal bag:

<idbag name="AddressHistory" table="t_PersonAddressHistory" lazy="true" cascade="all">
    <collection-id column="PersonAddressHistoryId" type="Int64"> <!--PersonAddressHistoryId is the t_PersonAddressHistory primary key. idbag requires the X table to have its own primary key. --> 
     <generator class="hilo" />
    </collection-id>
    <key column="PersonId" />
    <many-to-many class="AddressHistoryRecord" column="AddressHistoryRecordId" order-by="AtAddressSince"/>
</idbag>

The ordering happens in the many-to-many tag...

See NHibernate's documentation for more info on the idbag and what are it benefits over the normal bag but this is irrelevant to your question.

tolism7