Using Dapper to populate Enum properties

后端 未结 1 790
不思量自难忘°
不思量自难忘° 2021-02-02 08:36

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,

相关标签:
1条回答
  • 2021-02-02 09:05

    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.

    0 讨论(0)
提交回复
热议问题