Search code examples
c#nhibernateenumsfluent-nhibernate

NHibernate: map collection of enums using string and store as nvarchar


I have an enum type:

public enum CommunicationType
{
    [Description("Callback to client")]
    Callback
}

Which one use as a property of IList<CommunicationType> in class Partner:

public class Partner
{       
    public virtual long Id { get; set; }
    public virtual IList<CommunicationType> CommunicationTypes { get; set; }
}

My PartnerMap class looks like this:

public class PartnerMap : ClassMap<Partner>
{
    public PartnerMap()
    {
        Schema("tm");
        Table("Partner");

        Id(x => x.Id);

        HasMany(x => x.CommunicationTypes)
            .Schema("tm")
            .Table("PartnerCommunicationType")
            .KeyColumn("PartnerId")
            .Element("CommunicationType");
    }
}

One to many relation between Partner and CommunicationType i store in table [tm].[PartnerCommunicationType]:

PartnerId bigint
CommunicationType nvarchar(256)

What's my final goal: to store enums as nvarchar value and map it from table to IList<CommunicationType> from column CommunicationType of table [tm].[PartnerCommunicationTypes.

What's my problem: String was in incorrect format.

enter image description here

I tried to map CommunicationType as single property using Map(x=>x.CommunicationType) and this works great, but i can't do that with collection.

Is there a way i could map collection of enums and map it from nvarchar?

Edit: this answer should help me http://stackoverflow.com/a/22732415/2524304 but i can't understand how could i set type using FluentNHibernate.


Solution

  • This is the answer: Fluent NHibernate - How map an IList<Enum> as list of strings

    You have to use NHibernate.Type.EnumStringType<T> with your type as generic:

    HasMany(x => x.CommunicationTypes)
      .Schema("tm")
      .Table("PartnerCommunicationType")
      .KeyColumn("PartnerId")
      .Element("CommunicationType", part => part.Type<EnumStringType<CommunicationType>>());