如何让Dapper将.net日期时间映射到datetime2?

很简单,我正在将我们现有的系统从EF转换为Dapper。 由于各种公司原因,我们无法真正更改数据库,某些表具有DateTime2类型的列。 Dapper将任何.net DateTime转换为DbType.DateTime。

有人必须先遇到这种情况并找到一个简单的解决方案吗?

Dapper是一个单独的文件 ,包含在您的代码库中。 只需编辑文件:

替换(第300行):

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

附:

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

编辑:
在第319行附近,还有一个可以为空的DateTime进一步向下覆盖该映射块:

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

至:

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

现在在类似的问题中有一个更简单的解决方案:

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

这必须 INSERT 之前应用。 谢谢,@ Igand。