views:

235

answers:

2

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

A: 

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;}
Mauricio Scheffer
Nope, you must override SqlType. Otherwise, the SQL statement it will insert is:INSERT INTO TestTable (State, Id) VALUES ('Preview'::text,'9dea2a34-566a-45ea-84fd-24b86403ef5b'::uuid)
Mike
@Mike: ok, it's necessary to override it when you're using a database enum type. I changed my answer accordingly.
Mauricio Scheffer
A: 
ColumnType = typeof(EnumStringType<OrderState>).AssemblyQualifiedName
Fabio Maulo
Thanks, that helps a bit. However, you can't use EnumStringType directly because it will try to cast it to a 'text' datatype and cause a SQL error. That's why you have to override SqlType and make it a DbTYpe.Object. I did figure out I could do:[Property(SqlType = "TestEnum", ColumnType = "DB.PgEnumMapper`1[DB.OrderState, WebSite], WebSite")]...but your way is a bit cleaner..
Mike
.Net doesn't allow this, as attribute property values have to be static constant expressions: "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type". If ColumnType was of type System.Type it would be accepted though (without the "AssemblyQualifiedName")
Mauricio Scheffer