数据注释验证 returns 错误结果

Data Annotation Validation returns wrong result

这是我的整个程序。我希望它 return false 但结果是 true。我期望错误的结果还是我在这里做错了什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;


public class Program
{
    public static void Main()
    {
        var c = new Ax(){Id = 1000, Name = "A"};
        //c.Name = null; // when un-comment this, result as expected  
        var context = new ValidationContext(c);
        var isValid = Validator.TryValidateObject(c, context, null);

        Console.WriteLine(isValid);
    }


    public class Ax  
    {
        [Range(1,100)] // I expect this to cause failed validation
        public int Id{get; set;}
        [Required]
        public string Name { get; set; } 
    }
}

Result: true

您正在使用此方法:

Validator.TryValidateObject(Object, ValidationContext, ICollection<ValidationResult>)

This method evaluates each ValidationAttribute instance that is attached to the object type. It also checks whether each property that is marked with RequiredAttribute is provided. It does not recursively validate the property values of the object.

您应该使用另一个 overload 并将 true 作为第三个参数传递:

Validator.TryValidateObject (Object, 
                             ValidationContext, 
                             ICollection<ValidationResult>, Boolean)