【问题标题】:Unable to retrieve record using DateTime.Now in EntityFramework 6.1 with Code First approach无法通过代码优先方法在 EntityFramework 6.1 中使用 DateTime.Now 检索记录
【发布时间】:2014-09-23 10:42:36
【问题描述】:

我正在编写一些测试来检查验证程序是否按预期工作并且遇到了非常奇怪的行为。

测试方法内:

DateTime now = DateTime.Now;
using(CustomDbContext db = new CustomDbContext())
{
    Object1 o1 = new Object1();
    o1.CompletedOn = now;
    db.Object1s.Add(o1);
    db.SaveChanges();

    var query = from obj in db.Object1s
                where obj.CompletedOn == now
                select obj;

    Assert.AreNotEqual(query.Count(), 0);
}

我这样做的那一刻:

DateTime now = DateTime.Now;
using(CustomDbContext db = new CustomDbContext())
{
    Object1 o1 = new Object1();
    o1.CompletedOn = now;
    db.Object1s.Add(o1);
    db.SaveChanges();


    DateTime now2 = now.AddSeconds(-1);
    var query = from obj in db.Object1s
                where obj.CompletedOn > now2
                select obj;

    Assert.AreNotEqual(query.Count(), 0);
}

成功了。

在正常情况下我会认为now 持有对DataTime.Now 的引用,因此时间会改变。但是,调试器表明情况并非如此。两种情况下经过的时间相同,结果存储在数据库中

我正在使用 Code First Approach 来构建数据库,这就是 Object1:

class Object1
{
    [Key]
    public int Object1ID { get; set; }

    [Required]
    public DateTime CompletedOn { get; set; }
}

我使用 SQL Server 作为我的数据库。跟这个有关系吗?

可以存储在 SQL Server 中的值如下所示:2014-09-23 13:14:18.157

【问题讨论】:

  • DateTime 因此 DateTime.Now() 不是基于引用的,它是基于值的结构 - msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx
  • obj.CompletedOn > now2
  • @MikeMiller 是的,我想通了,这就是我问这个问题的原因。两次都应该相同,但我无法从数据库中检索结果。
  • 您在数据库中的CompletedOn 列是什么类型的?如果是datetime,其精度低于.NET DateTime 值,因此将其存储在数据库中会导致舍入。
  • @Tanner 好吧,我同意你的看法:如果我们有参考,情况就是这样,但正如 MikeMiller 所说:“它是一个基于值的结构”。所以我想这应该没什么区别。

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


【解决方案1】:

使用 SQL Profiler 查看发送的具体日期时间,您将看到存储值和参数值之间的差异。

【讨论】:

    【解决方案2】:

    上面的代码不起作用,因为由于某种未知原因,数据库中存储的值与DateTime 中作为参数给出的值之间似乎存在大约 +/-10 毫秒的差异。

    所以而不是使用:

    DateTime now2 = now.AddSeconds(-1);
    

    我可以使用:

    DateTime now2 = now.AddMilliseconds(-10);
    

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多