非常简单,我正在将现有系统从 EF 转换为 Dapper。由于各种公司原因,我们无法真正更改数据库,某些表具有 DateTime2 类型的列。 Dapper 将任何 .net DateTime 转换为 DbType.DateTime。
有人之前一定遇到过这个问题并找到了一个简单的解决方案?
现在在类似问题中有一个更简单的解决方案,但它是关于
string
。
对于
DateTime
:
SqlMapper.AddTypeMap(typeof(DateTime), System.Data.DbType.DateTime2);
这必须在之前应用任何数据库调用,例如
INSERT
。
您可以将其放在
Main
或 Startup
类中,或者在 Startup
上运行的任何位置来配置数据访问。 SqlMapper
是一个 static
类,更改适用于所有调用。
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.DateTimeOffset);
我不知道为什么当我尝试使用Datetime2时,我仍然不断丢失毫秒。 这个DateTimeOffset类型也是Datetime2。
日期值范围是从公元1年1月1日到公元9999年12月31日。时间值范围为 00:00:00 至 23:59:59.9999999,精度为 100 纳秒。时区值范围为 -14:00 至 +14:00。
提供的解决方案将全局映射类型,因为映射列表是静态的。
要为单个命令创建参数列表,更好的方法是使用
DynamicParameters
类。
var parameters = new DynamicParameters(template);
parameters.Add("@DateTimeParam", dateTimeValue, DbType.DateTime2);
await connection.ExecuteAsync(sql, parameters);
其中
template
可以是任何对象(包括之前使用的参数)。 template
属性将与添加的参数合并。