How to map a dictionary with a complex key type (C

2019-06-19 22:51发布

问题:

I have dictionary which I'm mapping using Fluent NHibernate. The dictionary has a complex key type CultureInfo. My database can't store that type so I want to use a string representation of it.

In mappings other than dictionary mappings, I can successfully map CultureInfo-properties using a user type convention. Now I wonder how to do it for dicationary mappings.

Here's the entity that contains the dictionary:

public class MultilingualPhrase : Entity
{
    private IDictionary<CultureInfo, string> languageValues;

    public virtual IDictionary<CultureInfo, string> LanguageValues
    {
        get
        {
            return languageValues;
        }
    }
}

And here's the auto mapping override for the entity:

public void Override(AutoMapping<MultilingualPhrase> mapping)
{
    mapping
        .HasMany(n => n.LanguageValues)
        .Access.ReadOnlyPropertyThroughCamelCaseField()
        .AsMap<string>("CultureName")
        .Element("Phrase")
        .Table("MultilingualPhraseValues");
}

This mapping (obviously) causes the following error:

Failed to convert parameter value from a CultureInfo to a String.

I know NHibernate has a type custom type implementation for CultureInfo (I'm using it for mapping properties) but how do I specify it in my mapping override?

回答1:

This works fine with FNH ClassMap (not sure about automapping) in NH 3.1 and FNH 1.2:

HasMany(n => n.LanguageValues)
    .Access.ReadOnlyPropertyThroughCamelCaseField()
    .AsMap<CultureInfo>("CultureName")
    .Element("Phrase")
    .Table("MultilingualPhraseValues");