See collection mapping in the reference documentation. There are several ways to map an IList
property.
A bag is an unordered, unindexed collection which may contain the same element multiple times.
<bag name="Transactions" lazy="true" table="Transaction" >
<key column="OrderId"/>
<one-to-many class="Transaction"/>
</bag>
A set is an unordered, unindexed collection which contains unique elements.
<set name="Transactions" lazy="true" table="Transaction" >
<key column="OrderId"/>
<one-to-many class="Transaction"/>
</set>
A list is an ordered and indexed collection which may contain the same element multiple times.
<list name="Transactions" lazy="true" table="Transaction" >
<key column="OrderId"/>
<index column="ordering"/>
<one-to-many class="Transaction"/>
</list>
NHibernate can return the unordered collections in sorted order using the sort attribute.
No discussion of collection mapping us complete without mentioning cascade. This enables operations on the parent entity to apply to the collection entities.
- It does not usually make sense to enable cascade on a
<many-to-one>
or <many-to-many>
association. Cascade is often useful for <one-to-one>
and <one-to-many>
associations.
- If the child object's lifespan is bounded by the lifespan of the parent object, make it a life cycle object by specifying cascade="all-delete-orphan".
- Otherwise, you might not need cascade at all. But if you think that you will often be working with the parent and children together in the same transaction, and you want to save yourself some typing, consider using cascade="persist,merge,save-update"