【问题标题】:EF DateTimes do not match saved values in SQL Server [duplicate]EF DateTimes 与 SQL Server 中保存的值不匹配 [重复]
【发布时间】:2015-08-12 22:03:30
【问题描述】:

我使用 C# Entity Framework 保存了一个日期时间,当我从数据库中加载该时间时,时间与我保存的值相差 1 毫秒或更多毫秒。

这是 C# 代码:

    public List<DateTime> TestDate()
    {
        var dates = new List<DateTime>();
        DateTime testvalue = DateTime.Now;
        dates.Add(testvalue);
        IactexGMG2Entities firstContext = new IactexGMG2Entities();
        var firstQuery = from p in firstContext.LocationProperties
                         where p.locationPropertyId == 4
                         select p;
        var firstRec = firstQuery.Single();
        firstRec.locationPropertyDateTime = testvalue;
        firstContext.SaveChanges();
        firstContext.Dispose();
         IactexGMG2Entities secondContext = new IactexGMG2Entities();
         var secondQuery = from p in secondContext.LocationProperties
                          where p.locationPropertyId == 4
                          select p;
        var secondRec = secondQuery.Single();

        var secondDate = secondRec.locationPropertyDateTime ?? DateTime.Now;
        dates.Add(secondDate);
        secondContext.Dispose();
        return dates;
    }

以下是接收到的值:

5/29/2015 5:43:25 PM . 154 , 635685182051540566
5/29/2015 5:43:25 PM . 153 , 635685182051530000

这是显示值的剃须刀代码:

@foreach (var date in Model)
{
    counter++;
    <div>
        @date . @date.Millisecond , @date.Ticks 
    </div>
}

如您所见,从数据库读回的第二个值比第一个值低 1.0566 毫秒。

变化量变化,正的和负的,总是以毫秒为单位。

有人知道日期值之间的转换是如何发生的吗?

注意:如果我使用相同的上下文来读取日期值,则值匹配。我认为这是因为它使用的是缓存值,而不是 SQL Server 值。

【问题讨论】:

  • SQL Server 中列的数据类型是什么? SQL Server 的datetime 类型不提供与System.DateTime 相同的分辨率。
  • 毫秒值从何而来?如果您将DateTime.Now(或DateTime.UtcNow)存储在数据库中,请考虑在保存之前将它们四舍五入到最接近的秒数。
  • 你看过这个帖子吗:stackoverflow.com/questions/7823966/…

标签: c# sql-server entity-framework datetime


【解决方案1】:

这实际上与实体框架几乎没有关系。截至 2008 年的 SQL Server 有两种 DateTime 类型:

DateTime

精度:四舍五入到 0.000、0.003 或 0.007 秒的增量

DateTime2

准确度:100 纳秒

使用 Code-First Annotations,您可以设置如下属性类型:

public MyClass
{
    [Column(“CreatedOn", TypeName="DateTime2")] 
    public DateTime CreatedOn { get; set; }
}

或者使用 Fluent API:

modelBuilder.Entity<MyClass>()
  .Property(p => p.CreatedOn)
  .HasColumnType("DateTime2");

【讨论】:

    【解决方案2】:

    问题在于 TSQL datetime 和 .NET DateTime 数据类型之间的分辨率不同

    datetime 的分辨率很小,并且四舍五入到 0.000、0.003 或 0.007 秒的增量,而 DateTime 的结果为 100ns

    只需使用新的datetime2 SQL 数据类型,它与 .NET 的 DateTime 具有相同的分辨率,无论如何建议在新工作中使用,正是针对您注意到的问题

    【讨论】:

      猜你喜欢
      • 2014-01-28
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 2019-04-27
      相关资源
      最近更新 更多