NHibernate: mapping a dictionary of lists
mapping, nhibernate
Solution
You can't directly map it. There are two rules to consider:
- Always use interfaces for collections (eg. `IList<T>`, `IDictionary<K,V>`)
- NH does not support nested collections. I've never seen an application for it before and never heard someone requesting it.
Put your list of string into a class and use interfaces:
class StringList
{
IList<string> Strings { get; private set; }
}
class Entity
{
private IDictionary<string, StringList> stringDict;
}
You might even see some advantages of having such a class.
Mapping:
<class name="Entity">
...
<map name="stringDict" table="Entity_StringDict" access="field">
<key column="Entity_FK"/>
<index column="Key" type="System.String"/>
<composite-element class="StringList">
<bag name="Strings" table="Entity_StringDict_Strings">
<key column="Entity_StringDict_FK"/>
<element type="System.String" column="String"/>
</bag>
</composite-element>
</map>
</class>
Maps to three Tables:
- Table `Entity`
- Table `Entity_StringDict`
- Column `Entity_FK`
- Column `Key`
- Table `Entity_StringDict_Strings`
- Column `Entity_StringDict_FK`
- Column `String`
Problem
My class has a field of type `Dictionary<string, List<string>>`. What's the best way to map it with NHibernate? I'd better leave it as a field, don't want to expose it. Thanks a lot! ulu