Reputation: 17671
I have an object in a simple test scenario that uses EF Code First and implements IValidatableObject. There's some very simple logic that adds a validation error and returns it back. There are also other validations on the object.
However, when saving the object - while the attribute based validations work - the IValidatableObject interface never seems to fire. Debugger doesn't step into it and the error never shows up with calling SaveChanges() or 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;
}
When I now try to add a customer and check for validation errors:
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();
}
I get ONE validation error for the company, but nothing from the IValidatableObject which should ALWAYS fail.
Any idea why?
Upvotes: 11
Views: 2968
Reputation: 46008
Quote from Jeff Handley's Blog Post on Validation Objects and Properties with Validator:
When validating an object, the following process is applied in Validator.ValidateObject:
- Validate property-level attributes
- If any validators are invalid, abort validation returning the failure(s)
- Validate the object-level attributes
- If any validators are invalid, abort validation returning the failure(s)
- If on the desktop framework and the object implements IValidatableObject, then call its Validate method and return any failure(s)
This indicates that what you are attempting to do won't work out-of-the-box because the validation will abort at step #2.
Upvotes: 11