简体   繁体   中英

Mapping Enums to Database with NHibernate/Castle ActiveRecord

There's a few other posts on mapping Enums to the DB with ActiveRecord, but none of them answer my question. I have an enum called OrderState:

public enum OrderState {InQueue, Ordered, Error, Cancelled}

And I have the following property on the table:

[Property(NotNull = true, SqlType = "orderstate", ColumnType = "DB.EnumMapper, WebSite")]
public OrderState State
{
   get { return state; }
   set { state = value; }
}

And I have the following type class:

public class EnumMapper : NHibernate.Type.EnumStringType<OrderState>
{
   public EnumMapper()
   {
   }

   public override NHibernate.SqlTypes.SqlType SqlType
   {
      get
      {
         return new NHibernate.SqlTypes.SqlType(DbType.Object);
      }
   }
}

Now this actually works the way I want, but the problem is I have tons of enums and I don't want to create a EnumMapper class for each one of them. Isn't there some way to just tell ActiveRecord to use DbType.Object for any enum? It seems to either want to be an integer or a string, but nothing else. This one's been driving me crazy for the last 2 hours..

Mike

Write a generic EnumStringType that overrides SqlType, then apply it:

public class EnumMapper<T> : NHibernate.Type.EnumStringType<T>
{
   public EnumMapper()
   {
   }

   public override NHibernate.SqlTypes.SqlType SqlType
   {
      get
      {
         return new NHibernate.SqlTypes.SqlType(DbType.Object);
      }
   }
}

apply it:

[Property(NotNull = true, 
          ColumnType = "MyNamespace1.EnumMapper`1[MyNamespace2.OrderState, MyAssembly2], MyNamespace1")]
public OrderState State {get;set;}

Unless I'm missing something, you can just do this:

public enum ExampleEnum
{ 
    Value1,
    Value2
}

[ActiveRecord]
public class ExampleClass 
{
    [PrimaryKey]
    public int ID { get; set; }

    [Property]
    public ExampleEnum Example { get; set; }
}

Seems to work perfectly for me.

ColumnType = typeof(EnumStringType<OrderState>).AssemblyQualifiedName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM