非常简单,我正在将现有系统从EF转换为Dapper。由于各种公司原因,我们无法真正更改数据库,某些表具有DateTime2类型的列。 Dapper将任何.net DateTime转换为DbType.DateTime。
有人必须先遇到这种情况并找到一个简单的解决方案吗?
答案 0 :(得分:34)
现在similar question中有一个更简单的解决方案:
SqlMapper.AddTypeMap(typeof(DateTime), System.Data.DbType.DateTime2);
这必须在 INSERT
之前应用。谢谢,@ Igand。
答案 1 :(得分:10)
Dapper在您的代码库中包含single file。只需编辑文件:
替换(第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;
答案 2 :(得分:1)
用于具有时区意识的日期和时间数据。
SqlMapper.AddTypeMap(typeof(DateTime), System.Data.DbType.DateTimeOffset);
我不知道为什么当我尝试使用Datetime2时,我仍然会丢失毫秒。 此DateTimeOffset类型也是Datetime2。
日期值范围是从公元1月1日至1月9999年12月31日。时间值范围是00:00:00到23:59:59.9999999,精度为100纳秒。时区的值范围是-14:00到+14:00。