Using Dapper to populate Enum properties

╄→гoц情女王★ 提交于 2019-12-03 06:36:35

问题


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);

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 ... ")

I get an error of the type

Error parsing column 2 (myEnum=1 - Byte)

Is there a way to use Dapper's Query() to fill in a class that contains properties which are enum types?


回答1:


Sure - as long as your enum agrees, i.e.

enum MyEnumType : byte {
    Foo, Bar, Blip, ...
}

then it will all work automatically.

(this limitation is by design, and shared with LINQ-to-SQL as it happens)

Alternatively, if the enum is : int and can't be changed, cast it in the SQL:

SELECT ..., CAST(x.myEnum as int) as myEnum, ...

Or finally, use the dynamic API:

foreach(var row in conn.Query(...)) { // note no <T>
    T obj = new Item { /* copy from row */ };
    ...
}

The first is my preferred object, as that enforces the byte data-type limitation throughout all your code, which is IMO a good thing.



来源:https://stackoverflow.com/questions/6086216/using-dapper-to-populate-enum-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!