NHibernate 验证器和 Null DateTime

发布于 2024-09-25 21:57:28 字数 865 浏览 0 评论 0原文

必须有一个简单的解决方案,我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空‖城人不在 2024-10-02 21:57:28

您需要使用可为空的类型。 DateTime 初始化为 DateTime.MinValue (1/1/0001)。尝试:

  [NotNull]
  public virtual DateTime? MySpecialDateProperty { get; set; }

You need to use a nullable type. DateTime is initialized to DateTime.MinValue (1/1/0001). Try:

  [NotNull]
  public virtual DateTime? MySpecialDateProperty { get; set; }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文