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

c# dapper

Question

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 ?

Accepted Answer

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;

Popular Answer

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.




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