简体   繁体   English

使用Dapper填充Enum属性

[英]Using Dapper to populate Enum properties

In using Dapper's Query() function, I am trying to fill in a class that has a property which is an enumerated value. 在使用Dapper的Query()函数时,我试图填充一个类,该类的属性为枚举值。 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: 在旧的ADO.NET方法中,我将在阅读器循环期间进行转换:

myClass.myEnum = (MyEnumType) reader.GetByte(2);

When using Dapper, I can't figure out how to do this conversion. 使用Dapper时,我不知道如何执行此转换。 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? 有没有一种方法可以使用Dapper的Query()来填充一个包含枚举类型属性的类?

Sure - as long as your enum agrees, ie 当然-只要您的枚举同意,即

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) (此限制是设计使然,并与LINQ-to-SQL共享)

Alternatively, if the enum is : int and can't be changed, cast it in the SQL: 或者,如果枚举是: int并且不能更改,则将其强制转换为SQL:

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

Or finally, use the dynamic API: 或者最后,使用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. 第一个是我的首选对象,因为它会在所有代码中强制执行byte数据类型限制,这对IMO来说是一件好事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM