PetaPoco处理枚举吗? [英] Does PetaPoco handle enums?

查看:113
本文介绍了PetaPoco处理枚举吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PetaPoco将表转换为POCO.

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

在我的表中,有一个名为TheEnum的列.此列中的值是代表以下枚举的字符串:

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在尝试将字符串"Fred"转换为MyEnum值时感到窒息.

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

它在GetConverter方法的以下行中执行此操作:

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

Convert.ChangeType( src, dstType, null );

在这里,src是"Fred"(a string),而dstTypetypeof(MyEnum).

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

例外是InvalidCastException,表示Invalid cast from 'System.String' to 'MyEnum'

我错过了什么吗?我需要先注册吗?

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

我通过在GetConverter方法中添加以下内容来解决该问题:

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.

所以,我的问题是,我需要做一些特殊的事情来向PetaPoco注册我的枚举吗?

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

2012年2月23日更新

提交了补丁程序前一阵子,但尚未被提取.如果要使用它,请查看补丁并合并到自己的代码中,或者仅获取代码

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.

推荐答案

您是正确的,PetaPoco并没有内置处理枚举的方法,通常我只是建议您完全按照自己的意愿做.

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

请注意,对于不使用枚举类型的请求,这不会降低速度. PetaPoco生成代码以将响应映射到pocos,因此只有在真正需要时才调用该委托.换句话说,仅在首次使用特定poco类型时才调用GetConverter,并且仅在枚举需要转换时才调用委托.不确定Enum.Parse的速度,但是是的,如果速度太慢,您可以将其缓存在字典中.

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.

这篇关于PetaPoco处理枚举吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆