2011-02-27 6 views
11

EF 코드 우선을 사용하고 IValidatableObject를 구현하는 간단한 테스트 시나리오에 개체가 있습니다. 유효성 검증 오류를 추가하고이를 리턴하는 아주 간단한 논리가 있습니다. 객체에 대한 다른 검증도 있습니다.EF 코드 첫 번째 : IValidatable 개체 유효성 검사 안 함

그러나 속성을 기반으로하는 유효성 검사가 작동하는 동안 개체를 저장할 때 IValidatableObject 인터페이스가 실행되지 않습니다. 디버거가 실행되지 않고 SaveChanges() 또는 GetValidationErrors()를 호출 할 때 오류가 나타나지 않습니다.

public class Customer : IValidatableObject { 
[Key] 
public int Id { get; set; } 

[StringLength(50)] 
[DisplayName("First Name")] 

public string FirstName { get; set; } 

[Required] 
[DisplayName("Last Name")] 
[StringLength(50)] 
public string LastName { get; set; } 

[Required] 
[StringLength(100)] 
public string Company { get; set; } 

[StringLength(200)] 
public string Email { get; set; } 

[DisplayName("Credit Limit")] 
public decimal CreditLimit { get; set; } 

[DisplayName("Entered On")] 
public DateTime? Entered { get; set; } 


public virtual ICollection<Address> Addresses { get; set; } 


public Customer() 
{ 
    Entered = DateTime.Now; 
    CreditLimit = 1000.00M; 

    Addresses = new List<Address>(); 
} 

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
{ 
    var results = new List<ValidationResult>(); 

    // add an error ALWAYS for testing - it doesn't show up 
    // and the debugger never hits this code 
    results.Add(new ValidationResult("Validate Added message",new [] { "Company" })); 

    return results; 
} 

지금 유효성 검사 오류에 대해 고객을 추가하고 확인하려고

:

public void AddNewCustomer() 
{ 
    Customer customer = new Customer(); 

    context.Customers.Add(customer); 

    customer.LastName = "Strahl"; 
    customer.FirstName = "Rick"; 
    customer.Entered = DateTime.Now; 
    //customer.Company = "West Wind"; // missing causes val error 

    var errorEntries = context.GetValidationErrors(); 
} 

내가 항상 실패 할 경우 IValidatableObject에서 ONE 검증 회사의 오류,하지만 아무것도 얻을.

왜 그런가?

답변

11

견적 Jeff Handley's Blog Post on Validation Objects and Properties with Validator에서 :

가 객체의 유효성을 검사 할 때, 다음 프로세스 Validator.ValidateObject 적용된다

  1. 유효성 속성 레벨 속성
  2. 임의의 검증 자라면 유효하지 않은 유효성 검사 유효성 검사를 반환 함 오류
  3. 검증 오브젝트 레벨이 어떤 검증이 유효하지 않은 경우
  4. 에서, 실패 (들)
  5. 하면 바탕 화면의 프레임 워크를 돌려 검증을 중단 속성 및 객체가 IValidatableObject를 구현, 다음의 유효성 검사 메서드를 호출하고 어떤 실패 (들)

이 검증 단계 # 2에서 중단하기 때문에 당신이하려고하는 어떤 것은 아웃 - 오브 - 박스 작동하지 않습니다 표시를 반환합니다.

+0

그래, 맞아. 다른 유효성 검사 오류가 없으면 IValidatableObject 코드가 실행됩니다. 이 동작에 대해서는 만족스럽지 않습니다. 사용자에게 적용되는 모든 오류를 표시하지 않는 것이 좋습니다. –

+2

@ 릭 - 동의합니다. 아마 조숙 한 최적화의 경우 일 것입니다 ... –

관련 문제