实体框架时间问题

时间:2015-04-27 12:13:20

标签: c# entity-framework

我遇到使用Entity Framework将时间插入数据库的问题。

背景:我在UTC时使用PC来构建此应用程序。构建完成后,我将它部署在UTC + 1服务器上。它连接的数据库也在UTC + 1服务器上。

因此,当我在本地运行到我的电脑上时,我放了一个时间,比如上午9点,它在上午10点保存在数据库中。这是预期的。

当我在服务器上运行时,我放入了上午9点的时间,它在上午11点保存在数据库中。这不是我的预期,因为它应该有一个小时差异而不是2.

任何人都可以帮忙解决这个问题。我目前的代码是:

     static void Main(string[] args)
    {
        DateTime Start = Convert.ToDateTime("27/04/2015 08:00");
        DateTime End = Convert.ToDateTime("27/04/2015 16:00");


        // generate a schedule
        ASML_ScheduleHeader schedule = new ASML_ScheduleHeader(); 
        schedule.ScheduleId = Guid.NewGuid();

        TimeZone localZone = TimeZone.CurrentTimeZone;     
        schedule.StartTime = localZone.ToLocalTime(DateTime.SpecifyKind(Start, DateTimeKind.Utc));
        schedule.EndTime = localZone.ToLocalTime(DateTime.SpecifyKind(End, DateTimeKind.Utc));           


        using (CIC40PrimaryEntities _context = new CIC40PrimaryEntities())
        {
            try
            {

                Console.WriteLine("Adding Header");
                _context.ASML_ScheduleHeader.Add(schedule);
                _context.SaveChanges();
                Console.WriteLine("Schedule added");

            }
            catch (Exception ex)
            {
                Console.WriteLine("Schedule not added");
            }

            Console.Read();
        } 
    }

1 个答案:

答案 0 :(得分:0)

我强烈建议您使用UTC,您始终可以将DateTime转换为表示层中的本地时间。

因此我会把它存储起来;

   @model byte[]

  <div style="width: 875px;">
    <object id="previewPdf" data="data:application/pdf;base64,@Convert.ToBase64String(Model)" style="overflow: visible;"/>
  </div>

如果你能给我们一些更明确的结果,也许是一些测试用例,那将会有所帮助:)