Dapper: is it possible to customize the type mapping of a specific field of a specific type?

20.3k views Asked by At

Let's say I have this User class:

public class User
{
    public int      ID          { get; set; }
    public string   FirstName   { get; set; }
    public string   LastName    { get; set; }
    public string   Email       { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime LastLogin   { get; set; }
}

Which I want to map to the following table:

CREATE TABLE "user" (
  "ID"          int(11) NOT NULL AUTO_INCREMENT,
  "FirstName"   varchar(45) DEFAULT NULL,
  "LastName"    varchar(45) DEFAULT NULL,
  "Email"       varchar(255) NOT NULL,
  "DateCreated" int(11) NOT NULL,
  "LastLogin"   int(11) NOT NULL,
  PRIMARY KEY ("ID")
)

Or put in simpler words: I want to store the DateTime properties as int fields in the database. However, this is the case for this class/table. Other class/tables might be mapped differently. I was thinking of something along the lines of a custom conversion function in combination with type or member map.

Is it possible to achieve this with Dapper, and if so how?

4

There are 4 answers

0
Amir Abiri On BEST ANSWER

The bottom line is that Dapper does not support this by design. One of its core design principles is a 1:1 mapping between the table and the object, with the exception of column names to property names mapping.

The solution I went with in the end was to combine Dapper with AutoMapper which we are already making heavy use of anyway. In our Dapper DAOs, in complex cases we use an entity object separate to the domain object and map between them. So essentially the non-trivial mapping between domain and table becomes a simple question of object-to-object mapping.

1
Dejan On

Probably you can use the new SqlMapper.SetTypeMap method to achieve this. See https://stackoverflow.com/a/12615036/331281 for more information.

8
Haney On

Dapper does not, to the best of my knowledge, currently support such conversions. You could use stored procs in Dapper, and have the proc do the conversion for you. You could also ensure that the data/conversion is done before passing the object to Dapper.

I heavily question why you'd opt for int dates vs DateTime however in your data source... Seems unnecessary and overly complex.

"Always write your code as if the next person to maintain it is an axe-wielding psychopath who knows your home address."

1
sigurd On

This should now be possible with custom SqlMapper.TypeHandler. See this example in unit tests. The downside is that it applies custom type handling to all fields of the same type. In your case all DateTime properties will be evaluated through type handler.