2014-04-29 6 views
0

엔티티를 비교할 때 ValidationAttribute 클래스를 확장하는 방법에 대해 머리를 터는 데 어려움을 겪고 있습니다.엔티티간에 날짜 시간 비교

예, 나는 다음과 같은 두 기관이 있습니다

고충 속성의 두 날짜 시간이라는 것을 (이 DLL은 여러 다른 프로젝트에서 사용하고있을 것입니다 때문에, 서버 측) 내가 유효성을 검사 할
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;} 
} 

해당 인시던트에 대한 IncidentDate 속성 뒤.

이상적으로 나는 클래스의 HearingDateAttribute : ValidationAttribute 유형을 쓰고 싶어,하지만 난이 IsValid 재정에 대한 비교 수행 할 IncidentDate 속성을 가져올 수 방법을 모르겠어요.

편집

확인이 작동하는 것 같다,하지만 난 그게 가장 좋은 방법입니다 모르겠어요 :

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; 
    } 
} 

답변

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

+0

나는 심지어 좋은 해결책이기 때문에 나는 그것을 사용하지 않는 경우에이 upvote에거야. –

0

당신은 당신의 Grievance 클래스처럼 뭔가를 쓸 수는

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

nullable datetime으로 검사를 중단하고 싶지는 않지만 확장 할 수 있다고 가정했습니다. fe :

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