我正在使用 Dapper 将我的实体映射到 SQL Server CE。如果我用 Kind=Utc
保存一个 DateTime
,当我读回它时,我得到一个 DateTime
和 Kind=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/