Is there an OrmLite option for DateTime.SpecifyKind(DateTimeKind.Utc)?
Asked Answered
C

1

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.

Contrive answered 2/9, 2013 at 21:28 Comment(1)
For those who may have landed on this page but are using OrmLite v3 with Sqlite dialect: there is a bug where if you persist a DateTime with a Kind of Utc, and a Milliseconds of 0, the Kind switches to Local when you read the DateTime back out.Horal
C
1

SqlServerOrmLiteDialectProvider.EnsureUtc(true) does work, there was something else going on with my test case that led me to believe that it didn't. Hopefully this will help someone else.

Here's some sample code:

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());
}

output

1,9/13/2013 5:19:12 PM,Utc,9/13/2013 10:19:12 AM,9/13/2013 5:19:12 PM
Contrive answered 13/9, 2013 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.