比较实体之间的DateTimes

时间:2014-04-29 15:34:46

标签: c# entity-framework data-annotations

当我想要跨实体进行比较时,我无法理解如何扩展ValidationAttribute类。

示例,我有以下两个实体:

public class Incident
{
    public DateTime IncidentDate {get;set;}
    //other properties

    public virtual ICollection<Grievance> Grievances {get;set;}
}

public class Grievance
{
    public DateTime FileDate {get;set;}
    public DateTime? HearingDate {get;set;}
    //other properties

    public virtual Incident Incident {get;set;}  
}

我想验证(服务器端,因为这个DLL将由多个不同的项目使用),Grievance属性的两个DateTime在相应事件的IncidentDate属性之后。

理想情况下,我想编写HearingDateAttribute : ValidationAttribute类的类,但我不确定如何让IncidentDate属性与IsValid覆盖进行比较。

修改

好的,这似乎有效,但我不确定这是最佳做法:

public sealed class HearingDateAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        var hearingDate = (DateTime)value;
        var grievance = (Grievance)context.ObjectInstance;
        var incidentDate = grievance.Incident.IncidentDate;

        if (hearingDate > incidentDate.Value)
        {
            return ValidationResult.Success;
        }

        return null;
    }
}

2 个答案:

答案 0 :(得分:1)

数据注释适用于触发单个属性的简单验证,但不适合模型级验证。您应该在您的实体上实施IValidatableObject。像这样:

public class Grievance: IValidatebleObject
{

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
     { 
         if (FileDate < Incident.IncidentDate 
            ||(HearingDate.HasValue && HearingDate.Value < Incident.IncidentDate)) 
         { 
             yield return new ValidationResult 
              ("Dates invalid", 
               new[] { "FileDate", “HearingDate”, "Incident.IncidentDate" }); 
         } 
     }  
}

参考:

http://msdn.microsoft.com/en-us/data/gg193959.aspx

答案 1 :(得分:0)

您可以为Grievance

编写类似的内容
public bool AreDatesBiggerThanIncident()
{
    return FileDate>Incident.IncidentDate && (HearingDate.HasValue? HearingDate.Value>Incident.IncidentDate : true);
}

我认为你不希望你的可空日期时间打破支票,但你可以扩展它,f.e:

public bool AreDatesBiggerThanIncident(bool returnFalseIfNullableEmpty=false)
{
    return FileDate>Incident.IncidentDate && (HearingDate.HasValue? HearingDate.Value>Incident.IncidentDate : !returnFalseIfNullableEmpty);
}