我在使用EF Code First并实现IValidatableObject的简单测试方案中有一个对象。有一些非常简单的逻辑可以添加验证错误并将其返回。该对象上还有其他验证。

但是,当保存对象时-尽管基于属性的验证有效-IValidatableObject接口(interface)似乎永远不会触发。调试器不会介入其中,并且调用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没有任何错误,它应该总是失败。

知道为什么吗?

最佳答案

引用Jeff Handley's Blog Post on Validation Objects and Properties with Validator:



这表明您尝试执行的操作无法立即使用,因为验证将在步骤2中终止。

10-08 17:32