DataReader转换为IList<T>

来源:互联网 发布:网络配线架有什么用 编辑:程序博客网 时间:2024/06/06 09:24

/// <summary>
        /// DataReader 转换成List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static IList<T> MapDataToEntity<T>(IDataReader dr) where T : new()
        {
            Type businessEntityType = typeof(T);
            IList<T> entitys = new List<T>();
            Hashtable hashtable = new Hashtable();
            PropertyInfo[] properties = businessEntityType.GetProperties();
            foreach (PropertyInfo info in properties)
            {
                hashtable[info.Name.ToUpper()] = info;
            }
            while (dr.Read())
            {
                T newObject = new T();
                for (int index = 0; index < dr.FieldCount; index++)
                {
                    PropertyInfo info = (PropertyInfo)hashtable[dr.GetName(index).ToUpper()];
                    if ((info != null) && info.CanWrite)
                    {
                        object drObj = dr.GetValue(index);
                        if (!(drObj is System.DBNull))
                        {
                            info.SetValue(newObject, drObj, null);
                        }
                    }
                }
                entitys.Add(newObject);
            }
            return entitys;
        }