6

Is there a way to specify that I want all of the DateTimes that OrmLite materializes to be set to UTC kind?

I store a lot of DateTimes in my database via stored procedures when a row is inserted:

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

When I retrieve the values via a select statement in ormlite, the datetimes come out in Unspecified kind (which is interpreted as the local timezone, I believe):

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

I would prefer not to set each DateTime object individually:

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

I found this question, but I don't think it's quite what I'm asking for:
servicestack ormlite sqlite DateTime getting TimeZone adjustment on insert

Also found this pull request, but setting SqlServerOrmLiteDialectProvider.EnsureUtc(true) doesn't seem to do it either.

4

1 回答 1

1

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

这是一些示例代码:

模型.cs

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

测试.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
于 2013-09-13T17:21:12.967 回答