PetaPoco 处理枚举吗?

2024-04-12

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

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

public enum MyEnum
{
    Fred,
    Wilma
}

当 PetaPoco 试图将字符串“Fred”转换为MyEnum value.

它在GetConverter方法,在行中:

Convert.ChangeType( src, dstType, null );

Here, src是“弗雷德”(astring), and dstType is typeof(MyEnum).

例外的是InvalidCastException,说Invalid cast from 'System.String' to 'MyEnum'

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

我通过将以下内容添加到中解决了这个问题GetConverter method:

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

显然,我不想在每一行上运行这个委托,因为它会大大减慢速度。我可以将这个枚举及其值注册到字典中以加快速度,但在我看来,类似的东西可能已经存在于产品中。

所以,我的问题是,我需要做什么特殊的事情才能向 PetaPoco 注册我的枚举吗?

2012 年 2 月 23 日更新

I 提交了补丁 https://github.com/toptensoftware/PetaPoco/pull/77有一段时间了,但还没有被拉进去。如果你想使用它,请查看补丁并合并到你自己的代码中,或者只获取代码从这里 http://stevedunns.blogspot.com/2011/08/fast-way-of-converting-c-enums-to.html.


我使用的是 4.0.3,PetaPoco 自动将枚举转换为整数并返回。但是,我想将枚举转换为字符串并返回。占(某人)的便宜Steve Dunn 的 EnumMapper http://stevedunns.blogspot.com/2011/08/fast-way-of-converting-c-enums-to.html和 PetaPoco 的IMapper,我想出了这个。多谢你们。

请注意,它不处理Nullable<TEnum>或数据库中的空值。要使用它,请设置PetaPoco.Database.Mapper = new MyMapper();

class MyMapper : PetaPoco.IMapper
{
    static EnumMapper enumMapper = new EnumMapper();

    public void GetTableInfo(Type t, PetaPoco.TableInfo ti)
    {
        // pass-through implementation
    }

    public bool MapPropertyToColumn(System.Reflection.PropertyInfo pi, ref string columnName, ref bool resultColumn)
    {
        // pass-through implementation
        return true;
    }

    public Func<object, object> GetFromDbConverter(System.Reflection.PropertyInfo pi, Type SourceType)
    {
        if (pi.PropertyType.IsEnum)
        {
            return dbObj =>
            {
                string dbString = dbObj.ToString();
                return enumMapper.EnumFromString(pi.PropertyType, dbString);
            };
        }

        return null;
    }

    public Func<object, object> GetToDbConverter(Type SourceType)
    {
        if (SourceType.IsEnum)
        {
            return enumVal =>
            {
                string enumString = enumMapper.StringFromEnum(enumVal);
                return enumString;
            };
        }

        return null;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PetaPoco 处理枚举吗? 的相关文章

随机推荐