/// <summary>
 /// 注册类型元数据描述类
 /// 常用于使用 System.ComponentModel.DataAnnotations.Validator 进行数据验证时批量注入 MetadataTypes
 /// </summary>
 public static void Register(Assembly assembly)
 {
     foreach (Type type in assembly.GetTypes())
     {
         AttributeCollection collection = TypeDescriptor.GetAttributes(type);
         foreach (var attr in collection)
         {
             MetadataTypeAttribute m = attr as MetadataTypeAttribute;
             if (m != null)
             {
                 TypeDescriptor.AddProviderTransparent(
                     new AssociatedMetadataTypeTypeDescriptionProvider(type, m.MetadataClassType), type);
             }
         }
     }
 }
Beispiel #2
0
        /// <summary>
        /// 通过使用验证上下文、验证结果集合和用于指定是否验证所有属性的值,确定指定的对象是否有效。
        /// </summary>
        /// <param name="instance">要验证的对象</param>
        /// <param name="validationContext">用于描述要验证的对象的上下文</param>
        /// <param name="validationResults">用于包含每个失败的验证的集合</param>
        /// <param name="breakOnFirstError">当第一个错误产生时,是否不再进行后续验证</param>
        /// <returns></returns>
        public static bool TryValidateObject(object instance, ValidationContext validationContext, ICollection <ValidationResult> validationResults, bool breakOnFirstError)//, Type metadataType = null)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (validationContext == null)
            {
                throw new ArgumentNullException("validationContext");
            }

            // 取当前实例的所有属性值
            IDictionary <ValidationContext, object>    propertyValues = XFrameworkValidator.GetPropertyValues(instance, validationContext);
            List <XFrameworkValidator.ValidationError> list           = new List <XFrameworkValidator.ValidationError>();

            // 取元数据描述
            Type metadataType = null;
            //if (metadataType == null)
            //{
            Type type = instance.GetType();
            MetadataTypeAttribute attr =
                TypeDescriptor
                .GetAttributes(type)
                .OfType <MetadataTypeAttribute>()
                .FirstOrDefault();

            if (attr != null)
            {
                metadataType = attr.MetadataClassType;
            }
            //}

            if (metadataType == null)
            {
                throw new NullReferenceException(string.Format("type {{{0}}} has no metadata descriptor.", type.Name));
            }
            PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties(metadataType);

            // 按照元数据属性的书写顺序逐个验证实体属性
            foreach (PropertyDescriptor des in descriptors)
            {
                KeyValuePair <ValidationContext, object> kv = propertyValues.FirstOrDefault(x => x.Key.MemberName == des.Name);
                ValidationContext context = kv.Key;
                object            value   = kv.Value;
                if (context != null)
                {
                    IEnumerable <ValidationAttribute> validationAttributes = XFrameworkValidator._store.GetPropertyValidationAttributes(context);
                    list.AddRange(XFrameworkValidator.GetValidationErrors(value, context, validationAttributes, breakOnFirstError));
                }
                if (list.Count > 0 && breakOnFirstError)
                {
                    break;
                }
            }

            bool result = true;

            foreach (var current in list)
            {
                result = false;
                if (validationResults != null)
                {
                    validationResults.Add(current.ValidationResult);
                }
            }

            return(result);
        }