Validator.TryValidateProperty不起作用

han*_*ign 9 .net c# validation data-annotations

我正在尝试实现Validator.TryValidateProperty,即使有[Required] 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; }
...
Run Code Online (Sandbox Code Playgroud)

这是返回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);
...
Run Code Online (Sandbox Code Playgroud)

小智 14

好的,刚刚找到了处理密封MetadataType类的解决方案.

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);
Run Code Online (Sandbox Code Playgroud)

我不得不添加以下内容:

TypeDescriptor.AddProviderTransparent
(new AssociatedMetadataTypeTypeDescriptionProvider
    (customer.GetType()), customer.GetType());
Run Code Online (Sandbox Code Playgroud)

在此地址找到解决方案:http: //forums.silverlight.net/forums/p/149264/333396.aspx