FluentNHibernate mapping for Dictionary

后端 未结 3 1696
深忆病人
深忆病人 2021-01-14 06:49

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

相关标签:
3条回答
  • 2021-01-14 07:19
    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.

    0 讨论(0)
  • 2021-01-14 07:24

    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.

    0 讨论(0)
  • 2021-01-14 07:27

    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.

    0 讨论(0)
提交回复
热议问题