Csharp/C#教程:如何让Dapper将.net日期时间映射到datetime2?分享


如何让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。

上述就是C#学习教程:如何让Dapper将.net日期时间映射到datetime2?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/984526.html

(0)
上一篇 2021年12月20日
下一篇 2021年12月20日

精彩推荐