NHibernate 验证器和 Null DateTime
必须有一个简单的解决方案,我正在尝试在 DateTime 属性上使用 NHibernate Validator 属性。如果该值为 null(通过 [NotNull]
),我希望它验证失败。当我提交 null 值时,它会转换为 1/1/0001 12:00:00 AM
并且 NHibernate 不会将其视为 null。我想我可以编写一个自定义验证规则,如果提交该日期则返回 false,但肯定有一个标准方法可以解决这个问题吗?
说明:这是一个示例类,
public class ExampleClass {
[NotNull]
public virtual DateTime MySpecialDateProperty { get; set; }
[NotNullOrEmpty]
public virtual string MyString { get; set; }
}
我有 NHibernate Validator 设置,以便在我的控制器中,我可以执行以下操作:
newExampleClass.IsValid()
如果为 true,它将保留在数据库中,如果不是我将返回 newExampleClass.ValidationResults()
当我创建 ExampleClass
的新实例时,MySpecialDateProperty
初始化为 1/1/0001 .. . 并且验证器不会将其视为空值。
编辑 2:我是否应该将 DateTime
设置为可空(DateTime?
),这会阻止 NHibernate 将值设置为最小 DateTime?
There must be a simple solution out there, I'm trying to use NHibernate Validator attributes on my DateTime properties. If the value is null (via [NotNull]
), I want it to fail validation. When I submit a null value it gets converted to 1/1/0001 12:00:00 AM
and NHibernate doesn't pick that up as null. I guess I could write a custom validation rule that returns false if that date is submitted, but surely there's a standard way around this?
Clarification: This is an example class,
public class ExampleClass {
[NotNull]
public virtual DateTime MySpecialDateProperty { get; set; }
[NotNullOrEmpty]
public virtual string MyString { get; set; }
}
I have NHibernate Validator setup so that in my controller, I can do:
newExampleClass.IsValid()
and if it is true it'll persist in the database, if not I'll return newExampleClass.ValidationResults()
When I create a new instance of ExampleClass
, the MySpecialDateProperty
initializes as 1/1/0001 ... and the validator doesn't pick that up as a null value.
Edit 2: Should I set DateTime
to nullable (DateTime?
) which would prevent NHibernate from setting the value to the minimum DateTime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用可为空的类型。 DateTime 初始化为 DateTime.MinValue (1/1/0001)。尝试:
You need to use a nullable type. DateTime is initialized to DateTime.MinValue (1/1/0001). Try: