Dapper - Sql to Object implicit cast from string to int

c# dapper

Question

I'm using dapper and am having issues with casting a string value from the db to an int. Has anyone overriden the TypeMap to allow for this?

Any suggestions would be great.

Accepted Answer

Dapper is picky about the types it maps. This protects you from all sorts of nasty errors that pop up later.

For example, your db could return:

  • 010hello
  • 10a10
  • 374837483748374837483748374834784378437438743874384738473

There is no clear course of action for mapping this kind of stuff to an Int32

That said, there are two strategies you can follow with dapper that do not require changes to IL generation.

Option 1: Shadow property

class Foo
{
   public int Age 
   { 
      get 
      { 
       int age; 
       int.TryParse(ageString, out age); 
       return age;  
      } 
   }
   string ageString;
}

\\ usage
cnn.Query<Foo>("select ageString from TableWithString");

Option 2, cast in SQL

cnn.Query<Bar>("select cast(ageString as int) Age from TableWithString");

There is no clean way to extend the mapping functionality in Dapper, if you do so you will be stuck needing to merge any fixes we add over time to your local copy.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why