Question

What is the best way of mapping a simple Dictionary property using Fluent NHibernate?

Was it helpful?

Solution

To map a list as a dictionary:

HasMany(x => x.Customers)
  .AsMap();

I have not used it; so cannot give an example.

Have look at the wiki: Cached version of the page, Actual page I have given the cached version of the page as the site seems to be down.

OTHER TIPS

public class PersistedData 
{
    public virtual IDictionary<key, value> Dictionary { get; set; }
}

public class PersistedDataMap : ClassMap<PersistedData>
{
    HasMany(x => x.Dictionary)
            .Table("dict_table")
            .KeyColumn("column_id")
            .AsMap<string>("key")
            .Element("value");
}

This will properly map Dictionary to table dict_table and use column_id to associate it to the base id.

As a side note, if you would like to use an Enum as the Key in the dictionary, it should be noted that NHibernate.Type.EnumStringType<MyEnum> can be used in place of the string in .AsMap<string> to use the string value instead of the Ordinal.

Using a simple class relationship such as the following:

public class Foo {
    public virtual IDictionary<string, Bar> Bars { get; set; }
}

public class Bar {
    public virtual string Type { get; set; }
    public virtual int Value { get; set; }
}

You can map this with Fluent NHibernate in this way:

mapping.HasMany(x => x.Bars)
       .AsMap(x => x.Type);

Where Bar.Type is used as the key field into the dictionary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top