随着“好友类”的概念,上面链接,以及数据注释我用这个方法extention。我忘了自己在哪里,对原作者如此赞赏。
我们使用它像
List<ValidationResult> errorList = new List<ValidationResult>();
bool bValid = client.IsValid<Client, ClientMetadata>(ref errorList, false);
public static bool IsValid<T, U>(this T obj, ref List<ValidationResult> errors, bool validateAllProperties = true) where T : IValidatableObject
{
//If metadata class type has been passed in that's different from the class to be validated, register the association
if (typeof(T) != typeof(U))
{
TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(T), typeof(U)), typeof(T));
}
var validationContext = new ValidationContext(obj, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(obj, validationContext, validationResults, validateAllProperties);
errors = validationResults;
if (validationResults.Count > 0)
return false;
else
return true;
}
但我怎么上的字段已经在实体添加属性?这不是重新定义吗? – Dani 2011-01-06 20:48:43