如何使用 Dapper 将 .NET DateTime 映射到数据库 DateTime2 以避免“SqlDateTime 溢出”异常?

问题描述 投票:0回答:4

我正在将现有系统从实体框架转换为 Dapper。由于各种公司原因,我们无法真正更改数据库。某些表的列类型为

DateTime2

Dapper 将任何 .NET

DateTime
转换为
DbType.DateTime
。这会导致异常:

System.Data.SqlTypes.SqlTypeException HResult = 0x80131930 消息=SqlDateTime 溢出。必须介于 1/1/1753 12:00:00 AM 和 12/31/9999 11:59:59 PM 之间。

有没有办法使用 Dapper 将 .NET

DateTime
映射到数据库
DateTime2

c# dapper
4个回答
61
投票

现在在类似问题中有一个更简单的解决方案,但它是关于

string

对于

DateTime

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

这必须在之前应用任何数据库调用,例如

INSERT

您可以将其放在

Main
Startup
类中,或者在
Startup
上运行的任何位置来配置数据访问。
SqlMapper
是一个
static
类,更改适用于所有调用。


9
投票

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;

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。


1
投票

提供的解决方案将全局映射类型,因为映射列表是静态的。

要为单个命令创建参数列表,更好的方法是使用

DynamicParameters
类。

var parameters = new DynamicParameters(template);
parameters.Add("@DateTimeParam", dateTimeValue, DbType.DateTime2);
    
await connection.ExecuteAsync(sql, parameters);

其中

template
可以是任何对象(包括之前使用的参数)。
template
属性将与添加的参数合并。

© www.soinside.com 2019 - 2024. All rights reserved.