Search code examples
ormpetapoco

Does PetaPoco handle enums?


I'm experimenting with PetaPoco to convert a table into POCOs.

In my table, I've got a column named TheEnum. The values in this column are strings that represent the following enum:

public enum MyEnum
{
    Fred,
    Wilma
}

PetaPoco chokes when it tries to convert the string "Fred" into a MyEnum value.

It does this in the GetConverter method, in the line:

Convert.ChangeType( src, dstType, null );

Here, src is "Fred" (a string), and dstType is typeof(MyEnum).

The exception is an InvalidCastException, saying Invalid cast from 'System.String' to 'MyEnum'

Am I missing something? Is there something I need to register first?

I've got around the problem by adding the following into the GetConverter method:

if (dstType.IsEnum && srcType == typeof(string))
{
  converter = delegate( object src )
            {
                return Enum.Parse( dstType, (string)src ) ;
            } ;
}

Obviously, I don't want to run this delegate on every row as it'll slow things down tremendously. I could register this enum and its values into a dictionary to speed things up, but it seems to me that something like this would likely already be in the product.

So, my question is, do I need to do anything special to register my enums with PetaPoco?

Update 23rd February 2012

I submitted a patch a while ago but it hasn't been pulled in yet. If you want to use it, look at the patch and merge into your own code, or get just the code from here.


Solution

  • You're right, handling enums is not built into PetaPoco and usually I just suggest doing exactly what you've done.

    Note that this won't slow things down for requests that don't use the enum type. PetaPoco generates code to map responses to pocos so the delegate will only be called when really needed. In other words, the GetConverter will only be called the first time a particular poco type is used, and the delegate will only be called when an enum needs conversion. Not sure on the speed of Enum.Parse, but yes you could cache in a dictionary if it's too slow.