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

后端 未结 7 2011
迷失自我
迷失自我 2020-11-27 11:04

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 Persistenc

7条回答
  •  无人及你
    2020-11-27 11:14

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

    The IUserTypeConvention is as @Julien's answer above: https://stackoverflow.com/a/1706462/878612

    public class EnumConvention : IUserTypeConvention
    {
        public void Accept(IAcceptanceCriteria 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(
                new EntityAutomapConfiguration())
                .Conventions.Setup(c =>
                    {
                        // Other IUserTypeConvention classes here
                        c.Add();
                    });
        }
    

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

        Kernel.Register(
            Component.For()
                .UsingFactoryMethod(() => CreateSessionFactory()),
                Component.For()
                .UsingFactoryMethod(k => k.Resolve().OpenSession())
                .LifestylePerWebRequest() 
        );
    

提交回复
热议问题