31

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?

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Slaggg
  • 6,381
  • 7
  • 28
  • 27
  • Note that if the datatype in SQLITE is "INT", then no special code is required to persist and retrieve .NET enums from Sqlite using Dapper. – BrokeMyLegBiking Feb 06 '12 at 21:40

1 Answers1

44

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    That worked! I was unaware that the in-memory storage type made such a difference. Thank you! – Slaggg May 22 '11 at 18:09
  • 31
    Careful, this can be dangerous if you don't explicitly set the values for your enums. You want to do enum MyEnumType : byte { Foo = 1, Bar = 2, Blip = 3, ... } If not, some junior developer will come behind you and insert Biz between Foo & Bar and redefine the values of anything after Biz. Those database values are now wrong. – xanadont Feb 24 '12 at 22:43
  • 1
    This makes perfect sense, but is a little unfortunate with respect to SQLite, which reports all integers as 64-bit numbers (meaning all `enum`s have to inherit `long` even if they only have a handful of values). I guess that's more of a limitation of SQLite than Dapper though :-) – Cameron Aug 04 '14 at 21:05
  • 3
    @Cameron https://github.com/StackExchange/dapper-dot-net/commit/9b0808d441d535fe6395c9241f3d82deb0ee8698 – Marc Gravell Aug 06 '14 at 12:15
  • @Cameron as far as I can see, just about everything now maps cleanly to just about everything – Marc Gravell Aug 06 '14 at 15:11