1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
public static T DataRowToModel<T>(DataRow dr) where T : new() { T t = new T(); if (dr == null) { return default(T); } PropertyInfo[] propertys = t.GetType().GetProperties(); DataColumnCollection Columns = dr.Table.Columns; foreach (PropertyInfo p in propertys) { string columnName = ((DBColumn)p.GetCustomAttributes(typeof(DBColumn), false)[0]).ColName; if (Columns.Contains(columnName)) { object value = dr[columnName]; if (!p.CanWrite || value is DBNull || value == DBNull.Value) { continue; }
try { #region SetValue switch (p.PropertyType.ToString()) { case "System.String": p.SetValue(t, Convert.ToString(value), null); break; case "System.Int32": p.SetValue(t, Convert.ToInt32(value), null); break; case "System.Int64": p.SetValue(t, Convert.ToInt64(value), null); break; case "System.DateTime": p.SetValue(t, Convert.ToDateTime(value), null); break; case "System.Boolean": p.SetValue(t, Convert.ToBoolean(value), null); break; case "System.Double": p.SetValue(t, Convert.ToDouble(value), null); break; case "System.Decimal": p.SetValue(t, Convert.ToDecimal(value), null); break; default: p.SetValue(t, value, null); break; } #endregion } catch (Exception) {
continue;
} } } return t; }
|