c# - 使用 Dapper 获取 UTC 日期时间

标签 c# .net orm utc dapper

我正在使用 Dapper 将我的实体映射到 SQL Server CE。如果我用 Kind=Utc 保存一个 DateTime,当我读回它时,我得到一个 DateTimeKind=Unspecified,这会导致各种问题。

例子:

var f = new Foo { Id = 42, ModificationDate = DateTime.UtcNow };
Console.WriteLine("{0} ({1})", f.ModificationDate, f.ModificationDate.Kind);
connection.Execute("insert into Foo(Id, ModificationDate) values(@Id, @ModificationDate)", f);
var f2 = connection.Query<Foo>("select * from Foo where Id = @Id", f).Single();
Console.WriteLine("{0} ({1})", f2.ModificationDate, f2.ModificationDate.Kind);

此代码提供以下输出:

20/09/2012 10:04:16 (Utc)
20/09/2012 10:04:16 (Unspecified)

我知道我应该使用 DateTimeOffset,但不幸的是 SQL CE 不支持这种类型。

有解决办法吗?我可以告诉 Dapper 假设所有日期都有 DateTimeKind.Utc 吗?更一般地说,我可以通过哪些选项来自定义映射?


编辑:我目前的解决方法是在 Dapper 实现结果后修补日期,但它有点味道......

var results = _connection.Query<Foo>(sql, param).Select(PatchDate);

...

static Foo PatchDate(Foo f)
{
    if (f.ModificationDate.Kind == DateTimeKind.Unspecified)
        f.ModificationDate = DateTime.SpecifyKind(f.ModificationDate, DateTimeKind.Utc);
    return f;
}

最佳答案

为前来寻求简单修复的任何其他人添加此答案。现在可以通过在 Dapper 中添加 SqlMapper.TypeHandler 来实现。

添加此类以将值从数据库转换为类型指定为 UTC 的日期时间。

public class DateTimeHandler : SqlMapper.TypeHandler<DateTime>
{
    public override void SetValue(IDbDataParameter parameter, DateTime value)
    {
        parameter.Value = value;
    }

    public override DateTime Parse(object value)
    {
        return DateTime.SpecifyKind((DateTime)value, DateTimeKind.Utc);
    }
}

然后在我的 Web API 的 Global.asax 文件中,我将类型处理程序添加到 dapper。

SqlMapper.AddTypeHandler(new DateTimeHandler());

如果您需要确保始终以 UTC 格式插入日期,那么您可以在 SetValue 方法上使用:

parameter.Value = DateTime.SpecifyKind(value, DateTimeKind.Utc);

关于c# - 使用 Dapper 获取 UTC 日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12510299/

相关文章:

java - 没有第三个表的一对多关联

c# - 当它们的字段实现 IDisposable 时,我该如何处理我的 Controller ?

c# - 单元测试 EF 数据模型

c# - 如何创建一个我可以使用的类的实例在 c# 中不止一个地方

c# - 为什么 System.Drawing Rectangle、Point、Size 等可变结构而不是类?

.net - 有人在真正的LOB应用程序中使用WPF吗?

java - 1 :M relationship in Hibernate and cascading operations

c# - 需要从字符串中动态拆分某些内容

c# - 如何使用控制台隐藏样式运行 C# 控制台应用程序?

php - 跨数据库连接学说