为什么EF在Time和DateTime值中修剪毫秒

时间:2012-11-20 08:08:22

标签: c# linq entity-framework datetime

我是从SQL Server 2008 R2 Express生成的ADO.NET实体数据模型,在我的表中我有时间或日期时间值。在datagrid中,此字段以毫秒正确显示,但在LINQ查询中使用我的ObjectSet<>我失去了几毫秒。为什么呢?

var query = from data in ctx.Data
            join member in ctx.Members
            on data.MemberId equals member.MemberId
            where member.StepId == (int)RepStepCombo.SelectedValue
            orderby data.Time ascending
            select new { 
                data.LaneNum, 
                member.MemberName, 
                data.Time, 
                mill = data.Time.Millisecond
            };

StreamWriter sw = new StreamWriter("text.txt");
foreach (var data in query)
{
    sw.WriteLine(data.LaneNum + " " + 
                 data.MemberName + " " + " millisec: " +
                 data.Time.ToString("HH:mm:ss.fff") + " " + 
                 data.mill);
}
sw.Close();
sw.Dispose();

1 个答案:

答案 0 :(得分:2)

你确定Time是DateTime而不是SmallDateTime吗? SmallDateTime具有较小的分辨率,并且不精确。

使用Sql2008和EF从datetime字段获取毫秒没有问题:

var members = from s in myEntites.TableName
              select s;

            foreach (TableEntry entry in members)
            {
                String time = ((DateTime)entry.date).ToString("HH:mm:ss.fff");
                Console.WriteLine(time);
            }

时间,转换为TimeSpan:

    var members = from s in myEntites.TableName
                  where s.myTime != null
                  select s;

    foreach (Entity myEntity in members)
    {
        String time = ((TimeSpan)myEntity.myTime).Milliseconds.ToString();
    }

“在我的机器上工作!” :)