2015-05-29 19 views
2

我使用C#Entity Framework保存日期時間,並且當我從數據庫加載該時間時,時間與我保存的值相差1毫秒或更多毫秒。EF DateTime與SQL Server中的保存值不匹配

下面是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值。

+5

什麼是數據類型的SQL Server中的列? SQL Server的'datetime'類型不提供與'System.DateTime'相同的分辨率。 – Dai

+0

毫秒值從哪裏來?如果您在數據庫中存儲'DateTime.Now'(或'DateTime.UtcNow'),請考慮將它們四捨五入到最接近的秒數,然後再保存它們。 – Dai

+0

你看過這篇文章:http://stackoverflow.com/questions/7823966/milliseconds-in-my-datetime-changes-when-stored-in-sql-server –

回答

6

問題是TSQL datetime和.NET之間的不同分辨率DateTime數據類型

日期時間僅具有小的分辨率,並且四捨五入爲0.000,0.003,或0.007秒增量,而日期時間有爲100ns

的resultion

只需使用新datetime2 SQL數據類型,它具有相同的分辨率.NET的日期時間,這是在新的工作反正建議,正是爲了這個問題你注意到

2

這其實已經很少與Entity Framewo無關RK。 SQL Server作爲2008有兩個日期時間類型:

DateTime

精度:以四捨五入取0.003的.000增量,或0.007秒

DateTime2

準確度:100納秒

利用二維碼的第一註釋您可以設置屬性的類型,如:

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

或者用流利的API:

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