I can validate Data Annotation and IValidatableObject when these one are on simple objects. However, in scenario where an object has a property that has to be validated, things get wrong.
public class BaseClass
{
public IEnumerable<ValidationResult> Validate()
{
var results = new List<ValidationResult>();
var validationContext = new ValidationContext(this, null, null);
Validator.TryValidateObject(this, validationContext, results, true);
return results;
}
}
public class Class1 : BaseClass, IValidatableObject
{
public Class1()
{
Property1 = new Class2();
}
public Class2 Property1 { get; set; }
//[Required]
public string AString1 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var e = new ValidationResult("Error from class1");
var s = Property1.Validate();
var r = new List<ValidationResult>(s) { e };
return r;
}
}
public class Class2 :BaseClass, IValidatableObject
{
public Class2()
{
Property2 = new Class3();
}
public Class3 Property2 { get; set; }
//[Required]
public string AString2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield return new ValidationResult("Error from class2");
}
}
public class Class3:BaseClass
{
//[Required]
public string AString3 { get; set; }
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var s = new Class1();
var results = s.Validate();
Assert.AreEqual(5, results.Count());
}
}
This small code snippet return 2 errors. The two that are from the Validate method of IValidatableObject. This is fine. However, if I uncomment the three "Required" data annotation I should have 5 errors (2 from Validate method and 3 froms Data Annotation).
Why when I uncomment the three data annotation that I have only one error "The AString1 field is required." which is the first class data annotation?
How can I have the five errors to be returned?