public static IList <T> GetManyTListBySQL <T>(string sql, DeleObjectName2ColumnName ObjectName2ColumnName, params SqlParameter[] parms) { IList <T> lists = new List <T>(); using (SqlDataReader rdr = SqlHelper.ExecuteReader(sql, parms)) { DataView dv = rdr.GetSchemaTable().DefaultView; while (rdr.Read()) { T objectT = (T)Activator.CreateInstance(typeof(T)); SetProperties(rdr, objectT, ObjectName2ColumnName, dv); lists.Add(objectT); } } return(lists); }
public static void SetProperties(System.Data.IDataReader dataReader, object Obj, DeleObjectName2ColumnName ObjectName2ColumnName, DataView dv) { System.Reflection.PropertyInfo[] propertyInfoList = Obj.GetType().GetProperties(); string columnName; foreach (System.Reflection.PropertyInfo property in propertyInfoList) { if (property.CanWrite) { columnName = ObjectName2ColumnName(property); object objValue = null; try { dv.RowFilter = "ColumnName='" + columnName + "'"; if (dv.Count > 0) { objValue = dataReader[columnName]; } } catch { objValue = null; } if (objValue != null && objValue != DBNull.Value) { objValue = ConvertDBNull(objValue, property.PropertyType); if (property.PropertyType == typeof(decimal) && objValue.GetType() != typeof(decimal)) { property.SetValue(Obj, Convert.ToDecimal(objValue), null); } else if (property.PropertyType == typeof(int) && objValue.GetType() != typeof(int)) { property.SetValue(Obj, Convert.ToInt32(objValue), null); } else if (property.PropertyType == typeof(bool) && objValue.GetType() != typeof(bool)) { property.SetValue(Obj, Convert.ToBoolean(objValue), null); } else { property.SetValue(Obj, objValue, null); } } } } }