无法使用Code First方法在EntityFramework 6.1中使用DateTime.Now检索记录

时间:2014-09-23 10:42:37

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

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

在测试方法中:

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

然后使用:

DateTime now2 = now.AddSeconds(-1);

我可以使用:

DateTime now2 = now.AddMilliseconds(-10);