问题描述
我有一个带有 DataAnnotation 属性的对象图,其中对象的某些属性是类,这些类本身具有验证属性,等等.
I have an object graph sprinkled with DataAnnotation attributes, where some properties of objects are classes which themselves have validation attributes, and so on.
在以下场景中:
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
没有值,那么我希望(并期望)一个异常,但我没有.这是我的做法:
If I try to validate an Employee
's Address
with no value for PostalCode
, then I would like (and expect) an exception, but I get none. Here's how I'm doing it:
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
还有哪些其他选项可以确保所有属性递归得到验证?
What other options do I have with Validator
that would ensure all properties are validated recursively?
推荐答案
这是选择加入属性方法的替代方法.我相信这将正确遍历对象图并验证所有内容.
Here's an alternative to the opt-in attribute approach. I believe this will traverse the object-graph properly and validate everything.
public bool TryValidateObjectRecursive<T>(T obj, List<ValidationResult> results) {
bool result = TryValidateObject(obj, results);
var properties = obj.GetType().GetProperties().Where(prop => prop.CanRead
&& !prop.GetCustomAttributes(typeof(SkipRecursiveValidation), false).Any()
&& prop.GetIndexParameters().Length == 0).ToList();
foreach (var property in properties)
{
if (property.PropertyType == typeof(string) || property.PropertyType.IsValueType) continue;
var value = obj.GetPropertyValue(property.Name);
if (value == null) continue;
var asEnumerable = value as IEnumerable;
if (asEnumerable != null)
{
foreach (var enumObj in asEnumerable)
{
var nestedResults = new List<ValidationResult>();
if (!TryValidateObjectRecursive(enumObj, nestedResults))
{
result = false;
foreach (var validationResult in nestedResults)
{
PropertyInfo property1 = property;
results.Add(new ValidationResult(validationResult.ErrorMessage, validationResult.MemberNames.Select(x => property1.Name + '.' + x)));
}
};
}
}
else
{
var nestedResults = new List<ValidationResult>();
if (!TryValidateObjectRecursive(value, nestedResults))
{
result = false;
foreach (var validationResult in nestedResults)
{
PropertyInfo property1 = property;
results.Add(new ValidationResult(validationResult.ErrorMessage, validationResult.MemberNames.Select(x => property1.Name + '.' + x)));
}
}
}
}
return result;
}
最新代码:https://github.com/reustmd/DataAnnotationsValidatorRecursive
包装:https://www.nuget.org/packages/DataAnnotationsValidator/
另外,我更新了这个解决方案来处理循环对象图.感谢您的反馈.
Also, I have updated this solution to handle cyclical object graphs. Thanks for the feedback.
这篇关于DataAnnotations:递归验证整个对象图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2