【问题标题】:How can I map enum properties to int in ServiceStack.OrmLite without using annotations?如何在不使用注释的情况下将枚举属性映射到 ServiceStack.OrmLite 中的 int?
【发布时间】:2020-01-03 13:48:12
【问题描述】:

我想从第三方库中序列化类。所以我不能使用注释。如何配置 ORMLite 将所有(或指定)枚举序列化为 int ?

编辑: 我找到了解决方案。我为给定类型注册了一个转换器:

OrmLiteConfig.DialectProvider.RegisterConverter<MY_ENUM_TYPE>(new 
ServiceStack.OrmLite.Converters.Int32Converter());

但不幸的是,它不能为所有枚举类型全局设置。

【问题讨论】:

  • edit您的问题包括您迄今为止尝试过的内容以及每次尝试的结果。

标签: c# ormlite-servicestack


【解决方案1】:

ServerStack 有一堆 ReflectionUtils,其中一个 Type.AddAttributes() 是在运行时向类型添加属性的简写。

通过使用来自外部程序集的枚举进行简单测试,我能够扫描该程序集中的所有枚举并附加 EnumAsIntAttribute。

我随后进行了快速测试,以确保它以整数形式插入到数据库中。

// Test class containing external enum.
public class Test
{
    [AutoIncrement]
    [PrimaryKey]
    public int? Id { get; set; }
    public ExternalEnum? EnumValue { get; set; }
}

// Use ExternalEnum type to get it's Assembly grab all export Enums.
IEnumerable<Type> types = typeof(ExternalEnum)
    .Assembly
    .GetExportedTypes()
    .Where(x => x.IsSubclassOf(typeof(Enum)));

// Loop through exported enums and add EnumAsIntAttribute.
foreach (Type type in types)
{
    type.AddAttributes(new EnumAsIntAttribute());
}

// Create Test table in DB.
db.CreateTableIfNotExists<Test>();

// Save to DB.
db.Save<Test>(new Test 
{ 
    EnumValue = ExternalEnum.SomeValue
});

编辑:修复了在 db.Save 中分配给 EnumValue 时使用的错误枚举类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多