问题描述
在使用Dapper的Query()函数时,我正在尝试填写一个具有枚举值属性的类。在我的数据库中,此列存储为一个字节。但是,在课堂上,他们是一个枚举。在旧的ADO.NET方法中,我会在阅读器循环期间进行转换:
In using Dapper's Query() function, I am trying to fill in a class that has a property which is an enumerated value. In my database, this column is stored as a byte. However, in the class, they are an enum. In the old ADO.NET approach, I'd convert during the reader loop:
myClass.myEnum = (MyEnumType) reader.GetByte(2);
使用Dapper时,我无法确定如何进行此转换。例如,当我执行类似
When using Dapper, I can't figure out how to do this conversion. For example when I do something like
myClass = conn.Query<MyClassType>("SELECT ... ")
我收到错误类型
Error parsing column 2 (myEnum=1 - Byte)
有没有使用Dapper的Query()方法来填充一个包含enum类型属性的类?
Is there a way to use Dapper's Query() to fill in a class that contains properties which are enum types?
谢谢。
推荐答案
当然 - 只要你的枚举同意,即
Sure - as long as your enum agrees, i.e.
enum MyEnumType : byte {
Foo, Bar, Blip, ...
}
然后它将全部自动工作。
then it will all work automatically.
(这个限制是设计的,并且与LINQ-to-SQL共享)
(this limitation is by design, and shared with LINQ-to-SQL as it happens)
或者,如果枚举是:int
并且无法更改,将其转换为SQL:
Alternatively, if the enum is : int
and can't be changed, cast it in the SQL:
SELECT ..., CAST(x.myEnum as int) as myEnum, ...
或者最后,使用 dynamic
API:
Or finally, use the dynamic
API:
foreach(var row in conn.Query(...)) { // note no <T>
T obj = new Item { /* copy from row */ };
...
}
第一个是我的首选对象,因为在所有代码中强制执行 byte
数据类型限制,这是一个好东西。
The first is my preferred object, as that enforces the byte
data-type limitation throughout all your code, which is IMO a good thing.
这篇关于使用Dapper填充枚举属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!