肯定有一个简单的解决方案,我正在尝试在我的 DateTime 属性上使用 NHibernate Validator 属性。如果该值为 null(通过 [NotNull]
),我希望它验证失败。当我提交一个空值时,它被转换为 1/1/0001 12:00:00 AM
并且 NHibernate 不会将其视为空值。我想我可以编写一个自定义验证规则,如果提交该日期则返回 false,但肯定有解决此问题的标准方法吗?
说明:这是一个示例类,
public class ExampleClass {
[NotNull]
public virtual DateTime MySpecialDateProperty { get; set; }
[NotNullOrEmpty]
public virtual string MyString { get; set; }
}
我有 NHibernate Validator 设置,所以在我的 Controller 中,我可以:
newExampleClass.IsValid()
,如果为真,它将保留在数据库中,否则我将返回 newExampleClass.ValidationResults()
当我创建 ExampleClass
的新实例时,MySpecialDateProperty
初始化为 1/1/0001 ... 并且验证器不会将其视为 null值(value)。
编辑 2:我是否应该将 DateTime
设置为可为空的 (DateTime?
),这会阻止 NHibernate 将值设置为最小 DateTime?
最佳答案
您需要使用可空类型。 DateTime 初始化为 DateTime.MinValue (1/1/0001)。尝试:
[NotNull]
public virtual DateTime? MySpecialDateProperty { get; set; }
关于NHibernate Validator 和 Null DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3831816/