How do you map an enum as an int value with fluent NHibernate?
Asked Answered
A

7

88

Question says it all really, the default is for it to map as a string but I need it to map as an int.

I'm currently using PersistenceModel for setting my conventions if that makes any difference.

Update Found that getting onto the latest version of the code from the trunk resolved my woes.

Alible answered 13/1, 2009 at 13:50 Comment(1)
Food for google bots: I was getting "illegal access to loading collection" before implementing this for my enum mapping.Busybody
L
83

The way to define this convention changed sometimes ago, it's now :

public class EnumConvention : IUserTypeConvention
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Property.PropertyType.IsEnum);
    }

    public void Apply(IPropertyInstance target)
    {
        target.CustomType(target.Property.PropertyType);
    }
}
Leopold answered 10/11, 2009 at 8:48 Comment(3)
This is the correct answer for the most recent version of fluent nhibernateSeller
This looks like it works fine for all enum types, but what if you want some as strings and some as ints? I think this should be configurable at the property mapping level.Silda
See the answer by @Mojica below that extends this to allow for nullable enums. #439503Kelson
A
45

So, as mentioned, getting the latest version of Fluent NHibernate off the trunk got me to where I needed to be. An example mapping for an enum with the latest code is:

Map(quote => quote.Status).CustomTypeIs(typeof(QuoteStatus));

The custom type forces it to be handled as an instance of the enum rather than using the GenericEnumMapper<TEnum>.

I'm actually considering submitting a patch to be able to change between a enum mapper that persists a string and one that persists an int as that seems like something you should be able to set as a convention.


This popped up on my recent activity and things have changed in the newer versions of Fluent NHibernate to make this easier.

To make all enums be mapped as integers you can now create a convention like so:

public class EnumConvention : IUserTypeConvention
{
    public bool Accept(IProperty target)
    {
        return target.PropertyType.IsEnum;
    }

    public void Apply(IProperty target)
    {
        target.CustomTypeIs(target.PropertyType);
    }

    public bool Accept(Type type)
    {
        return type.IsEnum;
    }
}

Then your mapping only has to be:

Map(quote => quote.Status);

You add the convention to your Fluent NHibernate mapping like so;

Fluently.Configure(nHibConfig)
    .Mappings(mappingConfiguration =>
    {
        mappingConfiguration.FluentMappings
            .ConventionDiscovery.AddFromAssemblyOf<EnumConvention>();
    })
    ./* other configuration */
Alible answered 14/1, 2009 at 8:44 Comment(4)
with "int mode" as the default. Who persists enums as strings?!Okhotsk
Could be a legacy database with string values already in therePicaroon
+1 hainesy. @ Andrew Bullock: answer to your question: anyone who deals with real world databases.Tetragon
Is there any IProperty interface in FN?Stephainestephan
M
40

Don't forget about nullable enums (like ExampleEnum? ExampleProperty)! They need to be checked separately. This is how it's done with the new FNH style configuration:

public class EnumConvention : IUserTypeConvention
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Property.PropertyType.IsEnum ||
            (x.Property.PropertyType.IsGenericType && 
             x.Property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) &&
             x.Property.PropertyType.GetGenericArguments()[0].IsEnum)
            );
    }

    public void Apply(IPropertyInstance target)
    {
        target.CustomType(target.Property.PropertyType);
    }
}
Mojica answered 26/4, 2010 at 19:27 Comment(3)
+1 For this addition! First version doesn't work for the nullable enums (they remain as strings).Peasant
@Mojica The column type in the database is int? And when the type accept Flags? Like: MyEnum.Active | MyEnum.PausedBedridden
@RidermandeSousaBarbosa: For flags check here: #2806161Mojica
O
25

this is how I've mapped a enum property with an int value:

Map(x => x.Status).CustomType(typeof(Int32));

works for me!

Onomatology answered 14/5, 2010 at 18:39 Comment(4)
My only qualm with this is that you have to remember to apply it to every enum. That's what the conventions were created for.Alible
This works for reading but failed when I tried a criteria query. Setting up a convention (see answer to this question) did work in all cases I tried though.Fulminant
Well I thought it was great - but this will cause problems: see this post. nhforge.org/blogs/nhibernate/archive/2008/10/20/…Silda
@Silda It seems that this has been fixed and is now recommended by James Gregory from the NH team: mail-archive.com/[email protected]/…Donettedoney
A
1

For those using Fluent NHibernate with Automapping (and potentially an IoC container):

The IUserTypeConvention is as @Julien's answer above: https://mcmap.net/q/236897/-how-do-you-map-an-enum-as-an-int-value-with-fluent-nhibernate

public class EnumConvention : IUserTypeConvention
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Property.PropertyType.IsEnum);
    }

    public void Apply(IPropertyInstance target)
    {
        target.CustomType(target.Property.PropertyType);
    }
}

The Fluent NHibernate Automapping configuration could be configured like this:

    protected virtual ISessionFactory CreateSessionFactory()
    {
        return Fluently.Configure()
            .Database(SetupDatabase)
            .Mappings(mappingConfiguration =>
                {
                    mappingConfiguration.AutoMappings
                        .Add(CreateAutomappings);
                }
            ).BuildSessionFactory();
    }

    protected virtual IPersistenceConfigurer SetupDatabase()
    {
        return MsSqlConfiguration.MsSql2008.UseOuterJoin()
        .ConnectionString(x => 
             x.FromConnectionStringWithKey("AppDatabase")) // In Web.config
        .ShowSql();
    }

    protected static AutoPersistenceModel CreateAutomappings()
    {
        return AutoMap.AssemblyOf<ClassInAnAssemblyToBeMapped>(
            new EntityAutomapConfiguration())
            .Conventions.Setup(c =>
                {
                    // Other IUserTypeConvention classes here
                    c.Add<EnumConvention>();
                });
    }

*Then the CreateSessionFactory can be utilized in an IoC such as Castle Windsor (using a PersistenceFacility and installer) easily. *

    Kernel.Register(
        Component.For<ISessionFactory>()
            .UsingFactoryMethod(() => CreateSessionFactory()),
            Component.For<ISession>()
            .UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
            .LifestylePerWebRequest() 
    );
Alexio answered 16/12, 2013 at 11:32 Comment(0)
D
0

You could create an NHibernate IUserType, and specify it using CustomTypeIs<T>() on the property map.

Dirkdirks answered 13/1, 2009 at 15:57 Comment(0)
L
0

You should keep the values as int / tinyint in your DB Table. For mapping your enum you need to specify mapping correctly. Please see below mapping and enum sample,

Mapping Class

public class TransactionMap : ClassMap Transaction
{
    public TransactionMap()
    {
        //Other mappings
        .....
        //Mapping for enum
        Map(x => x.Status, "Status").CustomType();

        Table("Transaction");
    }
}

Enum

public enum TransactionStatus
{
   Waiting = 1,
   Processed = 2,
   RolledBack = 3,
   Blocked = 4,
   Refunded = 5,
   AlreadyProcessed = 6,
}
Lombardi answered 24/4, 2014 at 15:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.