Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get Dapper to map .net datetime to datetime2?

Tags:

c#

dapper

Pretty simple, I'm converting our existing system from EF to Dapper. For various corporate reasons we can't really change the database, some of the tables have columns that are of type DateTime2. Dapper converts any .net DateTime to DbType.DateTime.

Someone must have bumped against this before and found an easy solution ?

like image 562
Dirk Avatar asked Jun 27 '12 17:06

Dirk


2 Answers

There's a much easier solution now in a similar question:

SqlMapper.AddTypeMap(typeof(DateTime), System.Data.DbType.DateTime2); 

This must be applied before INSERT's. Thanks, @Igand.

like image 69
John Tseng Avatar answered Sep 23 '22 17:09

John Tseng


Dapper is litterally a single file that you include into your code base. Just edit the file:

Replace (around line 300):

        typeMap[typeof(Guid)] = DbType.Guid;         typeMap[typeof(DateTime)] = DbType.DateTime;         typeMap[typeof(DateTimeOffset)] = DbType.DateTimeOffset;         typeMap[typeof(byte[])] = DbType.Binary; 

With:

        typeMap[typeof(Guid)] = DbType.Guid;         typeMap[typeof(DateTime)] = DbType.DateTime2;         typeMap[typeof(DateTimeOffset)] = DbType.DateTimeOffset;         typeMap[typeof(byte[])] = DbType.Binary; 

Edit:
There's also a nullable DateTime further down that block of mappings, around line 319:

        typeMap[typeof(DateTime?)] = DbType.DateTime;         typeMap[typeof(DateTimeOffset?)] = DbType.DateTimeOffset; 

To:

        typeMap[typeof(DateTime?)] = DbType.DateTime2;         typeMap[typeof(DateTimeOffset?)] = DbType.DateTimeOffset; 
like image 32
Randolpho Avatar answered Sep 22 '22 17:09

Randolpho