手动使用数据注释验证和对象图
假设我有两个简单的类:
public class CustomerDetails
{
[Required]
public string Address
{
get;
set;
}
}
public class Customer
{
public Customer()
{
Details = new CustomerDetails();
}
[Required]
public string Name
{
get;
set;
}
public CustomerDetails Details
{
get;
private set;
}
}
当我尝试以这种方式在控制台应用程序中手动验证 Customer 类时:
var customer = new Customer() { Name = "Conrad" };
var context = new ValidationContext(customer, null, null);
var results = new List<ValidationResult>();
Validator.TryValidateObject(customer, context, true);
然后 - 尽管我选择验证客户实例的所有属性 - 验证器仅验证客户实例的 Name 属性,但不是详细信息的 Address 属性。
这是设计使然还是我在这里遗漏了一些东西?此外,如果这是设计使然,那么是否有一种可靠的方法来手动验证用验证属性(包括嵌套类型)装饰的完整对象图,而不是手动对整个对象图使用验证器?
请注意,这是在控制台应用程序而不是 ASP.NET MVC 应用程序中进行测试的。
亲切的问候。
Let's assume that I have two simple classes:
public class CustomerDetails
{
[Required]
public string Address
{
get;
set;
}
}
public class Customer
{
public Customer()
{
Details = new CustomerDetails();
}
[Required]
public string Name
{
get;
set;
}
public CustomerDetails Details
{
get;
private set;
}
}
When I try to manually validate Customer class in a Console application in this way:
var customer = new Customer() { Name = "Conrad" };
var context = new ValidationContext(customer, null, null);
var results = new List<ValidationResult>();
Validator.TryValidateObject(customer, context, true);
Then -even though I chose to validate all properties of the customer instance- Validator just validates the Name property of the customer instance, but not the Address property of the Details.
Is this by design or am I missing something here? Moreover, if this is by design then is there a robust way to manually validate the full object graph decorated with validation attributes, including nested types instead of using validator for the whole object graph manually?
Please note that this is tested within a Console application and not an ASP.NET MVC application.
Kind regards.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我遇到了几乎相同的问题,但是涉及嵌套对象的集合。我能够通过在容器类上实现 IValidatableObject 来解决它。就你而言,这稍微容易一些。像这样的事情:
希望这有帮助。
I had almost the same problem but with the collection of nested objects. I was able to resolve it by implementing
IValidatableObject
on a container class. In your case it's slightly easier. Something like this:Hope this helps.