DateTime.SpecifyKind(DateTimeKind.Utc)是否有OrmLite选项?

时间:2013-09-02 21:28:22

标签: sql-server utc ormlite-servicestack

有没有办法指定我希望OrmLite具体化的DateTime全部设置为UTC类型?

插入行时,我通过存储过程在我的数据库中存储了很多DateTime

insert [Comment] (
  Body
, CreatedOn
) values (
  @Body
, getutcdate()
);

当我通过ormlite中的select语句检索值时,日期时间以Unspecified种出现(我相信它被解释为本地时区):

var comments = db.SqlList<Comment>("select * from [Comment] where ... ");

我希望分别设置每个DateTime对象:

foreach (var comment in comments) {
    comment.CreatedOn = DateTime.SpecifyKind(comment.CreatedOn, DateTimeKind.Utc);
}

我发现了这个问题,但我认为这不是我要求的:
servicestack ormlite sqlite DateTime getting TimeZone adjustment on insert

还找到this pull request,但设置SqlServerOrmLiteDialectProvider.EnsureUtc(true)似乎也没有。

1 个答案:

答案 0 :(得分:1)

SqlServerOrmLiteDialectProvider.EnsureUtc(true) 确实有用,我的测试用例还有其他事情让我相信它没有。希望这会帮助其他人。

以下是一些示例代码:

<强> model.cs

public class DateTimeTest {
    [AutoIncrement]
    public int Id { get; set; }
    public DateTime CreatedOn { get; set; }
}

<强> test.cs中

var connectionString = "server=dblcl;database=flak;trusted_connection=true;";
var provider = new SqlServerOrmLiteDialectProvider();
provider.EnsureUtc(true);
var factory = new OrmLiteConnectionFactory(connectionString, provider);
var connection = factory.Open();

connection.CreateTable(true, typeof(DateTimeTest));
connection.ExecuteSql("insert DateTimeTest (CreatedOn) values (getutcdate())");
var results = connection.SqlList<DateTimeTest>("select * from DateTimeTest");

foreach(var result in results) {
    Console.WriteLine("{0},{1},{2},{3},{4}", result.Id, result.CreatedOn, result.CreatedOn.Kind, result.CreatedOn.ToLocalTime(), result.CreatedOn.ToUniversalTime());
}

<强>输出

1,9/13/2013 5:19:12 PM,Utc,9/13/2013 10:19:12 AM,9/13/2013 5:19:12 PM