泛型导入丶验证和异常提示
泛型转换:
1 public class GhConvert<T> where T : new() 2 { 3 /// <summary> 4 /// 将DataTable转换成Model实体 5 /// </summary> 6 /// <param name="obj">Model名称</param> 7 /// <param name="dt">DataTable</param> 8 /// <returns></returns> 9 public static T ToObject(DataTable dt) 10 { 11 if (dt.Rows.Count <= 0) return new T(); 12 T t = new T(); 13 string tempName = ""; 14 PropertyInfo[] pis = t.GetType().GetProperties(); 15 foreach (PropertyInfo pi in pis) 16 { 17 tempName = pi.Name; 18 if (dt.Columns.Contains(tempName)) 19 { 20 // 判断此属性是否有Setter 21 if (!pi.CanWrite) continue; 22 object value = dt.Rows[0][tempName]; 23 if (value != DBNull.Value) 24 { 25 if (dt.Rows[0][pi.Name].GetType().Name.ToString().ToLower() == "datetime") 26 pi.SetValue(t, value.ToString(), null); 27 else 28 pi.SetValue(t, value, null); 29 } 30 } 31 } 32 return t; 33 } 34 /// <summary> 35 /// 36 /// </summary> 37 /// <typeparam name="T1"></typeparam> 38 /// <typeparam name="T2"></typeparam> 39 /// <param name="t1"></param> 40 /// <param name="t2"></param> 41 public static void ToObject<T1, T2>(T1 t1, T2 t2) 42 { 43 PropertyInfo[] t1Properties = t1.GetType().GetProperties(); 44 PropertyInfo[] t2Properties = t2.GetType().GetProperties(); 45 foreach (PropertyInfo p in t1Properties) 46 { 47 if (p == null) continue; 48 var t2Property = t2Properties.FirstOrDefault(m => m.Name == p.Name); 49 if (t2Property == null) continue; 50 object dstV = p.GetValue(t1, null); 51 object srcV = t2Property.GetValue(t2, null); 52 if (dstV != null && srcV != null) 53 if (dstV.ToString() == srcV.ToString()) continue; 54 p.SetValue(t1, srcV, null); 55 } 56 } 57 /// <summary> 58 /// 59 /// </summary> 60 /// <typeparam name="T2"></typeparam> 61 /// <param name="t2"></param> 62 /// <returns></returns> 63 public static T ToObject<T2>(T2 t2) 64 { 65 var t1 = new T(); 66 PropertyInfo[] t1Properties = t1.GetType().GetProperties(); 67 PropertyInfo[] t2Properties = t2.GetType().GetProperties(); 68 foreach (PropertyInfo p in t1Properties) 69 { 70 if (p == null) continue; 71 var t2Property = t2Properties.FirstOrDefault(m => m.Name == p.Name); 72 if (t2Property == null) continue; 73 object dstV = p.GetValue(t1, null); 74 object srcV = t2Property.GetValue(t2, null); 75 if (dstV != null && srcV != null) 76 if (dstV.ToString() == srcV.ToString()) continue; 77 p.SetValue(t1, srcV, null); 78 } 79 return t1; 80 } 81 /// <summary> 82 /// 将DataTable转换成IList 83 /// </summary> 84 /// <param name="dt">要转换的DataTable</param> 85 /// <returns>返回IList</returns> 86 public static IList<T> ToList(DataTable dt) 87 { 88 IList<T> list = new List<T>(); 89 string tempName = ""; 90 foreach (DataRow dr in dt.Rows) 91 { 92 T t = new T(); 93 // 获得此模型的公共属性 94 PropertyInfo[] propertys = t.GetType().GetProperties(); 95 foreach (PropertyInfo pi in propertys) 96 { 97 tempName = pi.Name; 98 // 检查DataTable是否包含此列 99 if (dt.Columns.Contains(tempName)) 100 { 101 // 判断此属性是否有Setter 102 if (!pi.CanWrite) continue; 103 object value = dr[tempName]; 104 if (value != DBNull.Value) 105 { 106 if (dr[pi.Name].GetType().Name.ToString().ToLower() == "datetime") 107 pi.SetValue(t, value.ToString(), null); 108 else 109 pi.SetValue(t, value, null); 110 } 111 } 112 } 113 list.Add(t); 114 } 115 return list; 116 } 117 /// <summary> 118 /// 119 /// </summary> 120 /// <param name="keys"></param> 121 /// <param name="dt"></param> 122 /// <returns></returns> 123 public static List<T> ToList(string keys, DataTable dt) 124 { 125 List<T> lists = new List<T>(); 126 string[] splitKeys = keys.Split(','); 127 PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 128 for (var row = 0; row < dt.Rows.Count; row++) 129 { 130 var t = new T(); 131 for (var column = 0; column < dt.Columns.Count; column++) 132 { 133 try 134 { 135 var value = dt.Rows[row][column].ToString(); 136 if (value == "") continue; 137 if (column > splitKeys.Count()) break; 138 PropertyInfo property = properties.FirstOrDefault(m => m.Name == splitKeys[column]); 139 if (property == null) continue; 140 if (value.GetType().Name.ToString().ToLower() == "datetime") 141 property.SetValue(t, value.ToString(), null); 142 else 143 property.SetValue(t, value, null); 144 } 145 catch (Exception e) 146 { 147 e.HelpLink = "导入数据第" + (row + 1) + "行" + dt.Columns[column].ColumnName + "数据格式有误!"; 148 throw e; 149 } 150 } 151 lists.Add(t); 152 } 153 return lists; 154 } 155 /// <summary> 156 /// 157 /// </summary> 158 /// <param name="ts"></param> 159 /// <returns></returns> 160 public static DataTable ToDataTable(IEnumerable<T> ts) { 161 var propertyInfos=new List<PropertyInfo>(); 162 Type type=typeof(T); 163 var dt=new DataTable(); 164 Array.ForEach<PropertyInfo>(type.GetProperties(),p=>{propertyInfos.Add(p);dt.Columns.Add(p.Name,p.PropertyType);}); 165 foreach(var item in ts){ 166 DataRow row=dt.NewRow(); 167 propertyInfos.ForEach(p=>row[p.Name]=p.GetValue(item,null)); 168 dt.Rows.Add(row); 169 } 170 return dt; 171 } 172 /// <summary> 173 /// 174 /// </summary> 175 /// <param name="keys"></param> 176 /// <param name="dt"></param> 177 /// <returns></returns> 178 public static Boolean IsColumnNamesEqual(string keys, DataTable dt) 179 { 180 var columnNames = (from DataColumn column in dt.Columns select column.ColumnName).ToList(); 181 string dtColumnNames = string.Join(",", columnNames); 182 return keys == dtColumnNames; 183 } 184 }
泛型导入:Excel导入使用了Aspose.Cell.dll
1 public class GhExcel<T> where T : new() 2 { 3 /// <summary> 4 /// 5 /// </summary> 6 /// <param name="keys"></param> 7 /// <param name="dt"></param> 8 /// <returns></returns> 9 public static List<T> ToList(string keys, DataTable dt) 10 { 11 return GhConvert<T>.ToList(keys, dt); 12 } 13 /// <summary> 14 /// 15 /// </summary> 16 /// <param name="fileName"></param> 17 /// <returns></returns> 18 public static DataTable ToDataTable(string fileName) 19 { 20 //var book = new Workbook(fileName); 21 //worksheet sheet = book.Worksheets[0]; 22 //Cells cells = sheet.Cells; 23 //DataTable dt = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColomn + 1, true); 24 return null; 25 } 26 /// <summary> 27 /// 28 /// </summary> 29 /// <param name="keys"></param> 30 /// <param name="dt"></param> 31 /// <returns></returns> 32 public static Boolean IsColumnNamesEqual(string keys, DataTable dt) 33 { 34 var columnNames = (from DataColumn column in dt.Columns select column.ColumnName).ToList(); 35 string dtColumnNames = string.Join(",", columnNames); 36 return keys == dtColumnNames; 37 } 38 /// <summary> 39 /// 40 /// </summary> 41 /// <param name="keys"></param> 42 /// <param name="dt"></param> 43 /// <returns></returns> 44 public static Boolean IsColumnCountEqual(string keys, DataTable dt) 45 { 46 string[] splitKeys = keys.Split(','); 47 return splitKeys.Count() == dt.Columns.Count; 48 } 49 }
泛型验证:使用了System.ComponentModel.DataAnnotations.Validator
1 public class GhValidation<T> 2 { 3 #region Cache 4 #endregion 5 6 #region Methods 7 /// <summary> 8 /// Validata<T>(List<T> lists) 9 /// </summary> 10 /// <typeparam name="T"></typeparam> 11 /// <param name="lists"></param> 12 /// <returns></returns> 13 public static List<ValidationResult> Validata(List<T> lists) 14 { 15 var vrs = new List<ValidationResult>(); 16 for (int i = 0; i < lists.Count; i++) 17 { 18 List<ValidationResult> vr = Validata(lists[i]); 19 foreach (var vd in vr) 20 { 21 vd.ErrorMessage = "第" + (i + 1) + "行," + vd.ErrorMessage; 22 } 23 vrs.AddRange(vr); 24 if (vr.Count > 3) 25 { 26 vrs = vrs.GetRange(0, 3); 27 vrs[vrs.Count - 1].ErrorMessage += "等......"; 28 break; 29 } 30 } 31 return vrs; 32 } 33 /// <summary> 34 /// Validata<T>(T t) 35 /// </summary> 36 /// <typeparam name="T"></typeparam> 37 /// <param name="t"></param> 38 /// <returns></returns> 39 public static List<ValidationResult> Validata(T t) 40 { 41 var vc = new ValidationContext(t, null, null); 42 var vr = new List<ValidationResult>(); 43 Validator.TryValidateObject(t, vc, vr, true); 44 return vr; 45 } 46 #endregion 47 }
泛型Orm
1 public class GhDbHelperSQL<T> 2 { 3 #region Cache 4 public List<String> SQLStringList=new List<string>(); 5 #endregion 6 7 #region EF 8 /// <summary> 9 /// 通过反射获得对象名称和自动增长ID 10 /// </summary> 11 /// <param name="obj">对象</param> 12 /// <returns>返回string[0]类名,string[1]自增ID</returns> 13 public static string[] GetModelInfo(T obj) 14 { 15 string[] str = new string[2]; 16 Type type = obj.GetType(); 17 object _TABLE = type.GetCustomAttributes(false)[0]; 18 if (_TABLE is TABLE) 19 { 20 TABLE _Tab = (TABLE)_TABLE; 21 str[0] = _Tab.Name; 22 str[1] = _Tab.AutoID; 23 } 24 //返回该Obj的名称以及ReturnAutoID的值 25 return str; 26 } 27 28 public int SaveChanges() { 29 return ExecuteSqlTran(SQLStringList); 30 } 31 32 public void Add(T obj) { 33 string[] ModelInfo = GetModelInfo(obj); 34 StringBuilder Columns = new StringBuilder(""); 35 StringBuilder Values = new StringBuilder(""); 36 Type t = obj.GetType(); 37 string sql = "insert into " + ModelInfo[0] + " ({0}) values ({1})"; 38 PropertyInfo[] pis = t.GetProperties(); 39 for (int i = 0; i < pis.Length; i++) 40 { 41 if (pis[i].GetValue(obj, null) == null) 42 continue; 43 if (pis[i].Name.ToString().ToLower() != ModelInfo[1].ToLower()) 44 { 45 Columns.Append(pis[i].Name.ToString()); 46 if (pis[i].PropertyType.Name.ToString().ToLower() == "datetime" || pis[i].PropertyType.Name.ToString().ToLower() == "string") 47 Values.Append("'" + pis[i].GetValue(obj, null).ToString().Trim().Replace("'", "''") + "'"); 48 else 49 Values.Append(pis[i].GetValue(obj, null).ToString().Trim().Replace("'", "''")); 50 51 Columns.Append(","); 52 Values.Append(","); 53 } 54 } 55 sql = string.Format(sql, Columns.ToString().TrimEnd(','), Values.ToString().TrimEnd(',')); 56 log.Debug("Insert 代码如下:"); 57 SQLStringList.Add(sql); 58 } 59 60 public void AddRange(List<T> ts) { 61 foreach (var t in ts) this.Add(t); 62 } 63 64 public void Update(T obj) { 65 string[] ModelInfo = GetModelInfo(obj); 66 StringBuilder Values = new StringBuilder(""); 67 string conditions = ModelInfo[1] + "="; 68 Type t = obj.GetType(); 69 string sql = "update " + ModelInfo[0] + " set "; 70 PropertyInfo[] pis = t.GetProperties(); 71 for (int i = 0; i < pis.Length; i++) 72 { 73 if (pis[i].GetValue(obj, null) == null || pis[i].GetValue(obj, null).ToString().Trim().Length <= 0) 74 continue; 75 if (pis[i].Name.ToString().ToLower() != ModelInfo[1].ToLower()) 76 { 77 Values.Append(pis[i].Name.ToString()); 78 Values.Append("="); 79 if (pis[i].PropertyType.Name.ToString().ToLower() == "datetime" || pis[i].PropertyType.Name.ToString().ToLower() == "string") 80 Values.Append("'" + pis[i].GetValue(obj, null).ToString().Trim().Replace("'", "''") + "'"); 81 else 82 Values.Append(pis[i].GetValue(obj, null).ToString().Trim().Replace("'", "''")); 83 Values.Append(","); 84 } 85 else 86 conditions += pis[i].GetValue(obj, null).ToString(); 87 } 88 sql = sql + Values.ToString().TrimEnd(',') + " where " + conditions; 89 log.Debug("Update 代码如下:"); 90 SQLStringList.Add(sql); 91 } 92 93 public void UpdateRange(List<T> ts) { 94 foreach (var t in ts) this.Update(t); 95 } 96 97 public void Remove(T obj) { 98 string[] ModelInfo = GetModelInfo(obj); 99 string sql = "Delete from " + ModelInfo[0] + " where " + ModelInfo[1] + "="; 100 Type t = obj.GetType(); 101 PropertyInfo[] pis = t.GetProperties(); 102 for (int i = 0; i < pis.Length; i++) 103 { 104 if (pis[i].Name.ToString().ToLower() == ModelInfo[1].ToLower()) 105 { sql += pis[i].GetValue(obj, null).ToString(); break; } 106 } 107 log.Debug("Delete:代码如下"); 108 SQLStringList.Add(sql); 109 } 110 111 public void RemoveRange(List<T> ts) { 112 foreach (var t in ts) Remove(t); 113 } 114 115 public void ExecuteSqls(string sql) 116 { 117 SQLStringList.Add(sql); 118 } 119 #endregion 120 }