我有一个洒有DataAnnotation属性的对象图,其中对象的某些属性是本身具有验证属性的类,等等。DataAnnotations:递归验证整个对象图
在以下情形:
public class Employee
{
[Required]
public string Name { get; set; }
[Required]
public Address Address { get; set; }
}
public class Address
{
[Required]
public string Line1 { get; set; }
public string Line2 { get; set; }
[Required]
public string Town { get; set; }
[Required]
public string PostalCode { get; set; }
}
如果我尝试验证的Employee
的Address
没有价值PostalCode
,那么我想(和期望)例外,但我得到没有。下面是我如何做它:
var employee = new Employee
{
Name = "Neil Barnwell",
Address = new Address
{
Line1 = "My Road",
Town = "My Town",
PostalCode = "" // <- INVALID!
}
};
Validator.ValidateObject(employee, new ValidationContext(employee, null, null));
我有什么其他的选择与Validator
,以确保所有的属性进行验证递归?
非常感谢提前。
+ 1为好的解决方案 – Jehof
不错,但收集呢?能够验证诸如“公共IList
地址”这样的属性是非常棒的。无论如何,感谢您的解决方案。 – altso该属性不为我评估。 –