使用 Entity Framework 迁移偏移 DateTime

Offsetting a DateTime using Entity Framework Migrations

我在 Azure 上托管的后端 API 上工作,我的日期返回时区不同。我目前获取日期的方式是在我的 Migrations 文件夹中使用自定义 Up() 方法,看起来类似于:

public partial class MyMigration : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.Users",
            c => new
                {
                    Created = c.DateTime(nullable: false, defaultValueSql: "GETDATE()"),
                })
            .PrimaryKey(t => t.ID);
 ... // 

(snippet source)

我一直在阅读有关 sysdatetimeoffset()datetimeoffset() 的内容,但我不知道如何在这种情况下使用它们。

问题

有没有一种方法可以使用 Entity Framework 代码优先迁移来设置数据库生成的默认 DateTime 和偏移量?

Azure 时间(SQL、网络应用程序、云服务)始终采用 UTC 时间。如果您希望特定时区的 API 到 return 时间,您最好使用 .NET 资源将 UTC 时间转换为您感兴趣的时区并让 Azure 处理 with/store UTC次。参见 Converting Times Between Time Zones on MSDN, specifically the section Converting UTC to a Designated Time Zone

DateTime timeUtc = DateTime.UtcNow;
try
{
   TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
   DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
   Console.WriteLine("The date and time are {0} {1}.", 
                     cstTime, 
                     cstZone.IsDaylightSavingTime(cstTime) ?
                             cstZone.DaylightName : cstZone.StandardName);
}
catch (TimeZoneNotFoundException)
{
   Console.WriteLine("The registry does not define the Central Standard Time zone.");
}                           
catch (InvalidTimeZoneException)
{
   Console.WriteLine("Registry data on the Central Standard Time zone has been corrupted.");
}