我正在尝试实现validator.tryValidateProperty,即使存在[必需的]dataAnnotation,tryValidateProperty也会返回有效的响应。
这是我的客户部分课程:
[MetadataType(typeof(Customer.Metadata))]
public partial class Customer : global::System.Data.Objects.DataClasses.EntityObject
{
...
private sealed class Metadata
{
[Required]
[SSNValidAttribute(ErrorMessage = "The SSN should be 9 numeric characters without any punctuation.")]
[DisplayName("SSN")]
public String SSN { get; set; }
...
下面是返回true的代码:
...
var customer = new Customer();
customer.SSN = "";
var vc = new ValidationContext(customer, null, null);
vc.MemberName = "SSN";
var res = new List<ValidationResult>();
var result = Validator.TryValidateProperty(customer.SSN, vc, res);
...
最佳答案
好的,刚刚找到了处理sealedMetadataType
类的解决方案。
var customer = new Customer();
TypeDescriptor.AddProviderTransparent
(new AssociatedMetadataTypeTypeDescriptionProvider
(customer.GetType()), customer.GetType());
customer.SSN = "";
var vc = new ValidationContext(customer, null, null);
vc.MemberName = "SSN";
var res = new List<ValidationResult>();
var result = Validator.TryValidateProperty(customer.SSN, vc, res);
我必须补充以下内容:
TypeDescriptor.AddProviderTransparent
(new AssociatedMetadataTypeTypeDescriptionProvider
(customer.GetType()), customer.GetType());
在以下地址找到解决方案:
http://forums.silverlight.net/forums/p/149264/333396.aspx