当前位置: 动力学知识库 > 问答 > 编程问答 >

fluent nhibernate - FluentNHibernate: Verifying Mappings

问题描述:

I can't configure my mapping file to work as expected. My model has a nullable DateTime property. These are my mapping.

...

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

...

And these are tests for verifying mappings.

...

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

.VerifyMappings();

But when I run this test, an ApplicationException is thrown:

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

网友答案:

then stating the type explicitly could do the trick

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

Original:

maybe the Copmiler inserts an implicit conversion of DateTime? to DateTime before returning the lambda, try:

.CheckProperty(e => (DateTime?)e.NullableDateTimeProperty, (DateTime?)DateTime.Now)
网友答案:

I know its an old question, but I managed to get the things working by creating a class to handle the equality check:

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();
    }
}

Then you use the equality comparer as the third parameter when calling CheckProperty:

.CheckProperty(e => e.NullableDateTimeProperty, DateTime.Now, new NullableDateTimeComparer())
分享给朋友:
您可能感兴趣的文章:
随机阅读: