日期:2014-05-20 浏览次数:21328 次
    [MetadataType(typeof(Employee.EmployeeMetadata))]
    public partial class Employee
    {
        internal sealed class EmployeeMetadata
        {
            [Display(Name = "用户编号", Order = 0, Description = "用户的唯一编号标志")]
            [Required(ErrorMessage = "用户编号自动生成")]
            [Editable(false)]
            public global::System.Int32 PersonnelID;
            [Display(Name = "名字", Order = 1, Description = "名字部分")]
            [Required(ErrorMessage = "必须输入名字")]
            [Editable(true)]
            [StringLength(20)]
            public global::System.String Firstname;
            //...以下属性省略
        }
    }
            Employee mod = new Employee();
            //...赋值赋值,从UI拿数据
            ValidationContext vc = new ValidationContext(mod, null, null);
            var validationResults = new List<ValidationResult>();
            Validator.TryValidateObject(mod, vc, validationResults, true);
            //就这里,无论我属性是什么他都没出错记录。
            //比如我Firstname设置成了“我们是党的好儿女,我们坚决拥护党的领导和决策,现在已经很多字了……反正就是比20长很多很多……”都不会报错。