验证日期时间流畅的nhibernate映射

Jes*_*sse 5 c# fluent-nhibernate

在一个非常简单的类上验证映射时,我遇到了一个问题.

System.ApplicationException:对于属性'Created'期望的相同元素,但是获得了具有相同值'8/9/2011 12:07:55 AM'的'System.DateTime'类型的不同元素.提示:在创建PersistenceSpecification对象时使用CustomEqualityComparer.

我已经尝试为equals创建覆盖并获取hashcode方法,这导致了相同的错误.我挖到了持久性规范测试的自定义相等比较器,并再次遇到同样的错误.我或许应该在早上用一双清新的眼睛来看看这个,但我觉得我错过了一些非常基本的东西.

谢谢大家.

public class Blah
{
    public int Id { get;  set; }
    public DateTime Created { get; set; }
    public string Description { get; set; }
}

[Test]
public void Can_Correctly_Map_Blah()
{
    new PersistenceSpecification<Blah>(Session)
        .CheckProperty(c => c.Id, 1)
        .CheckProperty(c => c.Description, "Big Description")
        .CheckProperty(c => c.Created, System.DateTime.Now)
        .VerifyTheMappings();
}
Run Code Online (Sandbox Code Playgroud)

Col*_*e W 11

在比较日期时间时你必须要小心,因为它们似乎是相同的,但它们可以变化到滴答(100纳秒).它可能失败了,因为sql server没有准确存储日期时间.

您需要使用自定义相等比较器,以便您只能比较年,月,日,小时,分钟和秒.

看看这篇文章: 为什么datetime无法比较?


Eth*_*anB 5

我只是在使用内存中的SQLite会话时遇到此问题。我对其进行了调试,发现DateTimes的“毫秒”和“种类”属性有所不同(“ Utc”种类与“未指定”)。

我根据Cole W的建议实施:

class DateTimeEqualityComparer : IEqualityComparer
{
    private TimeSpan maxDifference;

    public DateTimeEqualityComparer(TimeSpan maxDifference)
    {
        this.maxDifference = maxDifference;
    }

    public bool Equals(object x, object y)
    {
        if (x == null || y == null)
        {
            return false;
        }
        else if (x is DateTime && y is DateTime)
        {
            var dt1 = (DateTime)x;
            var dt2 = (DateTime)y;
            var duration = (dt1 - dt2).Duration();
            return duration < maxDifference;
        }
        return x.Equals(y);
    }

    public int GetHashCode(object obj)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

您的规格测试将变成这样:

var maxDifference = TimeSpan.FromSeconds(1);
...
new PersistenceSpecification<Blah>(Session)
    ...
    .CheckProperty(c => c.Created, System.DateTime.Now,
            new DateTimeEqualityComparer(maxDifference))
Run Code Online (Sandbox Code Playgroud)