Dapper:将字符串转换为枚举

时间:2015-02-18 09:04:03

标签: c# .net dapper

我是Dapper的新手,我正在试图弄清楚它是否可以将数据库字符串映射到枚举;它默认情况下不会发生在我身上。

例如,假设我使用此SQL

select customer_type from customers

和这个班级

public class Customer
{
    ...
    public CustomerType CustomerType { get; set; }
    ...
}

使用此枚举

public enum CustomerType
{
     Unknown,
     SomeCustomerType,
     ...
}

在这种情况下,我总是以默认的枚举值(Unknown)结束,而不是从数据库中映射字符串值。

任何人都知道如何实现这一目标?

编辑: 我知道这可以使用数字字段,因为数字将转换为枚举,但这样做的缺点是必须确保数据库ID和枚举保持同步。我正在寻找类似但有字符串的东西。

1 个答案:

答案 0 :(得分:0)

如果您将列名称别名设置为与您的属性同名的名称:

#! /usr/bin/env python3 import _thread import time TIMEOUT = 60 def main(): interrupt_main_after(TIMEOUT) count = run_addition_loop() print('About', round(count / TIMEOUT, 3), 'numbers were added per second.') def interrupt_main_after(seconds): def interrupter(): time.sleep(seconds) _thread.interrupt_main() _thread.start_new_thread(interrupter, ()) def run_addition_loop(): count = 0 try: while True: count += 1 except KeyboardInterrupt: return count if __name__ == '__main__': main()

如果数据库中customer_type字段的值有任何值,您还可以使用replace函数删除空格。

相关问题