Monday 5 March 2007

How to map to a Generic IDictionary

Say you have a standard nHibernate Bag that maps to a IList

C# Definition

public virtual IList<UserGroup> Groups;


nHibernate Mapping

<bag name="UserGroups" table="UserGroup">
<key column="UserID"/>
<one-to-many class="UserGroup"/>
</bag>


You can change this to a IDictionary by changing the IList to a IDictionary in the Business Entity, then change the bag to a map,and adding a index setting to the nHibernate mapping.

So the above would be changed to

C# Definition

public virtual IDictionary<int,UserGroup> Groups;


nHibernate Mapping

<map name="UserGroups" table="UserGroup">
<key column="UserID"/>
<index column="GroupID" type="int"/>
<one-to-many class="UserGroup"/>
</map>


Where of course the index column is the column that you will search on, and the type is the type of the column.

NOTE - The Key Column and the Index column cannot be the same, but then thinking about that it would be pointless because the key value would be the same on all the keys of the dictionary.