c# - 验证 datetime fluent nhibernate 映射

标签 c# fluent-nhibernate

我在验证一个非常简单的类的映射时遇到问题。

System.ApplicationException : For property 'Created' expected same element, but got different element with the same value '8/9/2011 12:07:55 AM' of type 'System.DateTime'. Tip: use a CustomEqualityComparer when creating the PersistenceSpecification object.

我已经尝试为 equals 和 get 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();
}

最佳答案

比较日期时间时必须小心,因为它们可能看起来相同,但它们可能会小到刻度(100 纳秒)。它可能失败了,因为 sql server 没有准确地存储日期时间。

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

也看看这篇文章: Why datetime cannot compare?

关于c# - 验证 datetime fluent nhibernate 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6992106/

相关文章:

nhibernate - 将多对多关系映射为 IDictionary

c# - 如何使用带有客户端证书的 (Microsoft.AspNetCore.TestHost)TestServer

c# - 将手机注册为 HID(鼠标)

c# - 安装的默认数据

c# - 如何使用 nhibernate SchemaUpdate 功能更改列

fluent-nhibernate - 映射枚举列表

c# - 将一长串参数包装为单个对象

c# - 使用 BART 的 API 通过 RestSharp C# 获取响应

c# - 如果 Not Null,则 AutoMapper 映射嵌套对象的属性

c# - Fluent NHibernate (ASP.NET MVC) 中的枚举类型不匹配