/// <summary> /// 验证模型 /// 包括Attribute规则和Fluent规则 /// </summary> /// <typeparam name="T">模型类型</typeparam> /// <param name="model">模型实例</param> /// <returns></returns> public static ValidResult ValidFor <T>(T model) { if (model == null) { return(ValidResult.False("模型不能为null ..")); } var context = new ValidContext(model, RuleProperty.GetGetProperties(typeof(T))); foreach (var property in context.Properties) { var failureRule = property.GetFailureRule(context); if (failureRule != null) { var message = failureRule.FormatErrorMessage(null); return(ValidResult.False(message, property.Info)); } } return(ValidResult.True()); }
/// <summary> /// 获取表达式的属性 /// </summary> /// <typeparam name="T">模型类型</typeparam> /// <typeparam name="TKey">属性类型</typeparam> /// <param name="keySelector">属性选择</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> /// <exception cref="NotSupportedException"></exception> /// <returns></returns> public static RuleProperty GetProperty <T, TKey>(Expression <Func <T, TKey> > keySelector) { if (keySelector == null) { throw new ArgumentNullException("keySelector"); } var body = keySelector.Body as MemberExpression; if (body == null) { throw new ArgumentException("表达式必须为MemberExpression ..", "keySelector"); } if (body.Member.DeclaringType.IsAssignableFrom(typeof(T)) == false || body.Expression.NodeType != ExpressionType.Parameter) { throw new ArgumentException("无法解析的表达式 ..", "keySelector"); } var propertyInfo = body.Member as PropertyInfo; if (propertyInfo == null) { throw new ArgumentException("表达式选择的字段不是属性 ..", "keySelector"); } var property = RuleProperty .GetGetProperties(typeof(T)) .FirstOrDefault(item => item.Info == propertyInfo); if (property == null) { throw new NotSupportedException(string.Format("属性{0}.{1}不支持验证 ..", typeof(T).Name, propertyInfo.Name)); } return(property); }