无法使用DateTime检索记录.现在在EntityFramework 6.1中使用代码优先方法

本文关键字:代码 方法 EntityFramework 检索 DateTime 记录 | 更新日期: 2023-09-27 18:23:59

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

测试方法内:

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的引用,因此时间会发生变化。然而,调试器表明情况并非如此。两种情况下经过的时间相同,结果存储在数据库中。

我正在使用代码优先的方法来构建数据库这就是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检索记录.现在在EntityFramework 6.1中使用代码优先方法

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

上面的代码不起作用,因为不知什么原因,数据库中存储的值和DateTime中给定的参数之间似乎有+/-10ms的差异。

因此,与其使用:

DateTime now2 = now.AddSeconds(-1);

我可以使用:

DateTime now2 = now.AddMilliseconds(-10);