【发布时间】: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)存储在数据库中,请考虑在保存之前将它们四舍五入到最接近的秒数。
标签: c# sql-server entity-framework datetime