Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper - Sql to Object implicit cast from string to int

Tags:

c#

dapper

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.

like image 747
Omnia9 Avatar asked Aug 15 '11 17:08

Omnia9


1 Answers

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.

like image 53
Sam Saffron Avatar answered Oct 08 '22 04:10

Sam Saffron