FluentNHibernate:验证映射

时间:2011-12-07 20:55:54

标签: fluent-nhibernate

我无法配置我的映射文件以按预期工作。我的模型具有可为空的DateTime属性。这些是我的映射。

...
Map(e => e.NullableDateTimeProperty).Nullable();
...

这些是验证映射的测试。

...
.CheckProperty(e => e.NullableDateTimeProperty, (DateTime?)DateTime.Now)
.VerifyMappings();

但是当我运行此测试时,抛出了一个ApplicationException:

System.ApplicationException : For property 'NullableDateTimeProperty' expected type 'System.DateTime' but got 'System.Nullable`1[[System.DateTime]]'

2 个答案:

答案 0 :(得分:0)

然后明确说明类型可以做到这一点

.CheckProperty(e => e.NullableDateTimeProperty, (DateTime?)DateTime.Now, (e, value) => e.NullableDateTimeProperty = value)

原件:

也许Copmiler会插入DateTime的隐式转换?返回lambda之前的DateTime,尝试:

.CheckProperty(e => (DateTime?)e.NullableDateTimeProperty, (DateTime?)DateTime.Now)

答案 1 :(得分:0)

我知道这是一个老问题,但我设法通过创建一个类来处理相等检查来使事情发生:

public class NullableDateTimeComparer : IEqualityComparer
{
    public new bool Equals(object x, object y)
    {
        var a = x as DateTime?;
        var b = y as DateTime?;

        if (a == null && b == null)
            return true;

        if (a == null || b == null)
            return false;

        //there is some milliseconds difference between a and b
        //so a.Value == b.Value fails
        return a.Value.Subtract(b.Value).Seconds == 0;
    }

    public int GetHashCode(object obj)
    {
        return obj == null ? 0 : obj.GetHashCode();
    }
}

然后在调用CheckProperty时使用相等比较器作为第三个参数:

.CheckProperty(e => e.NullableDateTimeProperty, DateTime.Now, new NullableDateTimeComparer())