/// <summary> /// 获取对象的列 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static Dictionary <string, string> GetExeclTitleByTitleAttribute <T>() { List <ExeclTitleAttribute> list = new List <ExeclTitleAttribute>(); //取属性上的自定义特性 Type objType = typeof(T); //遍历对象的所有属性 foreach (PropertyInfo propInfo in objType.GetProperties()) { //得到指定的特性 ExeclTitleAttribute attr = propInfo.GetCustomAttribute <ExeclTitleAttribute>(); if (attr != null) { if (attr.ColumnIndex.HasValue == false) { attr.ColumnIndex = 0; } attr.PropName = propInfo.Name; list.Add(attr); } } //按照排序字段进行排序 list = list.OrderBy(o => o.ColumnIndex).ToList(); //转成表头字典并且返回 return(list.ToDictionary(key => key.PropName, value => value.TitleName)); }
/// <summary> /// table转业务对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <returns></returns> public static IList <T> ModelConver <T>(this DataTable table) { // 定义集合 IList <T> entityList = new List <T>(); // 获得此模型的类型 Type type = typeof(T); foreach (DataRow dr in table.Rows) { T entity = System.Activator.CreateInstance <T>(); // 获得此模型的公共属性 PropertyInfo[] propertys = entity.GetType().GetProperties(); //标准表头:实体定义的 List <string> standardHead = new List <string>(); //错误信息 List <ErrorMessage> errorMessages = new List <ErrorMessage>(); foreach (PropertyInfo propertyInfo in propertys) { //判断是否有这个特性 ExeclTitleAttribute execlTitleAttribute = propertyInfo.GetCustomAttribute <ExeclTitleAttribute>(); if (execlTitleAttribute == null) { continue; } if (table.Columns.Contains(execlTitleAttribute.TitleName)) { if (execlTitleAttribute.ColumnIndex == null) { //得到该列的位置索引 int index = table.Columns.IndexOf(execlTitleAttribute.TitleName); execlTitleAttribute.ColumnIndex = index; } standardHead.Add(execlTitleAttribute.TitleName); // 判断此属性是否有Setter if (propertyInfo.CanWrite == false) { continue; } object value = dr[execlTitleAttribute.TitleName]; if (value != null) { execlTitleAttribute.ErrorMessage = propertyInfo.SetPropertyInfoValue(entity, value); //将错误信息添加到错误集合 if (string.IsNullOrEmpty(execlTitleAttribute.ErrorMessage) == false) { ErrorMessage err = new ErrorMessage { Name = propertyInfo.Name, ErrMsg = execlTitleAttribute.ErrorMessage }; errorMessages.Add(err); } } } } #region 设置异常列信息 PropertyInfo errorMessagePropertyInfo = entity.GetType().GetProperty("ErrorMessages"); if (errorMessagePropertyInfo != null && errorMessages.Count > 0) { errorMessagePropertyInfo.SetValue(entity, errorMessages, null); } #endregion AddOtherColumns(table.Columns, standardHead, dr, entity); entityList.Add(entity); } return(entityList); }