NHiberate验证程序的开始日期早于结束日期。

| 使用Nhibernate Validator(具有S#harp体系结构/ MVC3),如何编写自定义属性,最好不是特定于对象的属性(因为这是相当普遍的要求),以强制执行PropertyA> = PropertyB(或者在更一般的情况下,两者都可以为null)。 就像是
public DateTime? StartDate { get; set; }

[GreaterThanOrEqual(\"StartDate\")]
public DateTime? EndDate { get; set; }
我看到我可以在特定的
Entity
类中覆盖ѭ1but,但是我不确定这是否是最好的方法,在这种情况下我也看不到如何提供消息。     
已邀请:
当您需要比较对象的多个属性作为验证的一部分时,您需要一个分类验证器。然后将属性应用于类,而不是属性。 我认为没有一个可以做自己想要的事,但是编写自己的事很容易。 这是一个代码概述,大致向您展示验证器的外观
[AttributeUsage(AttributeTargets.Class)]
[ValidatorClass(typeof(ReferencedByValidator))]
public class GreaterThanOrEqualAttribute : EmbeddedRuleArgsAttribute, IRuleArgs
{        
    public GreaterThanOrEqualAttribute(string firstProperty, string secondProperty)
    {
        /// Set Properties etc
    }
}

public class ReferencedByValidator : IInitializableValidator<GreaterThanOrEqualAttribute>
{       
    #region IInitializableValidator<ReferencedByAttribute> Members

    public void Initialize(GreaterThanOrEqualAttribute parameters)
    {
        this.firstProperty = parameters.FirstProperty;
        this.secondProperty = parameters.SecondProperty;
    }

    #endregion

    #region IValidator Members

    public bool IsValid(object value, IConstraintValidatorContext constraintContext)
    {
       // value is the object you are trying to validate

        // some reflection code goes here to compare the two specified properties
   }
    #endregion

}
}     
当前,如果需要在模型上执行此操作,则可以使用模型实现
IValidatableObject
public class DateRangeModel : IValidatableObject {

   public DateTime StartDate { get; set; }
   public DateTime EndDate { get; set; }


   public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        List<ValidationResult> results = new List<ValidationResult>();
        if (StartDate > EndDate)
        {
            results.Add(new ValidationResult(\"The Start Date cannot be before the End Date.\", \"StartDate\"));
        }
        return results;
    }
这似乎可以与现有系统很好地集成。缺点是,由于此方法未应用于域对象,因此,如果在其他地方使用了不同的模型,则也需要从那里(或在创建域对象的服务层中)使用其他逻辑来强制执行此操作。创建或更新域对象。     

要回复问题请先登录注册