Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store enum as string in database

Tags:

c#

enums

orm

dapper

I am experimenting with dapper. I have a class which has an enum and the values are stored as strings in the database.

This works with FluentNHibernate using GenericEnumMapper

Is it possible to do the same with Dapper?

like image 859
Yavor Shahpasov Avatar asked May 31 '11 19:05

Yavor Shahpasov


2 Answers

This is not built in at the moment, there is a proposed solution for this here: http://code.google.com/p/dapper-dot-net/issues/detail?id=24 which we are yet to decide on. I like the idea of extensible type converters

As it stands the cleanest way to do this would be to define shadow property eg:

class MyType
{
   public MyEnum MyEnum {get; private set;}
   private string DBEnum { set { MyEnum = Convert(value);} }

   private MyEnum Convert(string val)
   {
     // TODO: Write me 
   } 
}

// cnn.Query<MyType>("select 'hello' as DBEnum")  <-- will set MyEnum
like image 76
Sam Saffron Avatar answered Oct 17 '22 22:10

Sam Saffron


From the sample code I've just tried, it appears not. You can map an enum to its underlying integer value, but if you try to map it to its string value, a DataException is thrown.

like image 2
adrianbanks Avatar answered Oct 17 '22 20:10

adrianbanks