Correctly convert DateTime property with Dapper on SQLite

dapper datetime sqlite3

Question

I'm using Dapper to insert and get objects to/from SQLite: one object have a property of type DateTime (and DateTimeOffset) that I have to persist and retrieve with milliseconds precision. I can't find a way to correctly retrieve the value because Dapper fail with:

    System.FormatException : String was not recognized as a valid DateTime.
   in System.DateTimeParse.ParseExactMultiple(String s, String[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style)
   in System.DateTime.ParseExact(String s, String[] formats, IFormatProvider provider, DateTimeStyles style)
   in System.Data.SQLite.SQLiteConvert.ToDateTime(String dateText, SQLiteDateFormats format, DateTimeKind kind, String formatString)
   in System.Data.SQLite.SQLite3.GetDateTime(SQLiteStatement stmt, Int32 index)
   in System.Data.SQLite.SQLite3.GetValue(SQLiteStatement stmt, SQLiteConnectionFlags flags, Int32 index, SQLiteType typ)
   in System.Data.SQLite.SQLiteDataReader.GetValue(Int32 i)
   in System.Data.SQLite.SQLiteDataReader.GetValues(Object[] values)
   in Dapper.SqlMapper.<>c__DisplayClass5d.<GetDapperRowDeserializer>b__5c(IDataReader r) in SqlMapper.cs: line 2587
   in Dapper.SqlMapper.<QueryImpl>d__11`1.MoveNext() in SqlMapper.cs: line 1572
   in System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   in System.Linq.Enumerable.ToList(IEnumerable`1 source)
   in Dapper.SqlMapper.Query(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in SqlMapper.cs: line 1443
   in Dapper.SqlMapper.Query(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in SqlMapper.cs: line 1382

What do I have to try? Column is of type DATETIME.

Do I have to create a custom TypeHandler and convert DateTime to and from a SQLite string in format "o"?

Dapper version 1.38

Popular Answer

I have found that custom TypeHandler for base types can't be used because of default typeMap that is choosen before looking for TypeHandler.

I have opened an issue dapper-dot-net but in the mean time I have solved replacing via reflection the default typeMap with a new one like the previous minus the four key DateTime, DateTime?, DateTimeOffset, DateTimeOffset?




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