FluentNHibernate mapping for Dictionary

巧了我就是萌 提交于 2019-12-01 09:25:34
dbones

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.

Craig Russell
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.

JD Courtoy

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!