Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent Nhibernate Enum Mapping

I have some problem with enum mapping in fluent NHibernate. I know this question has been asked many times but I couldn't find any solution that worked for me. I'm newbie in NHibernate and it looks like I may have missed something simple and stupid. Here is my code.

public class DBPublication
{
    public virtual int pub_id { get; set; }
    public virtual PublicationStatuses status { get; set; }
    ...
}

public enum PublicationStatuses 
{
    on_moderation,
    active,
    ...
}


public class DBPublicationMap : ClassMap<DBPublication>
{
    public DBPublicationMap()
    {
        Table("content.publications");
        Id(x => x.pub_id).GeneratedBy.Sequence("content.pub_sq");           
        Map(x => x.status);
        ...
    }
}

postgres enum type

CREATE TYPE content.enum_publication_status AS ENUM('on_moderation', 'active', ...);

but when I try to save, postgres throws this

column "status" is of type content.enum_publication_status but expression is of type text

any suggestion?

like image 951
maxs87 Avatar asked Oct 04 '12 09:10

maxs87


1 Answers

Here is a working sample of configuring nhibernate to store enum field.

public class Entity
{
    public virtual int id { get; set; }

    public virtual SomeEnum EnumField { get; set; }
}

public enum SomeEnum
{
    Value1,
    Value2
}

class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        Id(x => x.id).GeneratedBy.Native();
        Map(x => x.EnumField);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var factory = Fluently.Configure().Mappings(x => x.FluentMappings.AddFromAssemblyOf<Entity>())
                                .ExposeConfiguration(config => new SchemaExport(config).Create(false, true))
                                .Database(MsSqlConfiguration.MsSql2008.ConnectionString("Data Source=.;Initial Catalog=nhtest;Integrated Security=True"))
                                .BuildSessionFactory();
        using (var session = factory.OpenSession())
        {
            using (var transaction = session.BeginTransaction())
            {
                var entity = new Entity();
                entity.EnumField = SomeEnum.Value2;
                session.Save(entity);
                transaction.Commit();
            }
        }

    }
}

In such case it is stored as strings in data base. If you want it be saved as integers, you need to change mapping for Enum field property to the following:

Map(x => x.EnumField).CustomType<int>();
like image 173
Sly Avatar answered Sep 28 '22 09:09

Sly