Exemplo n.º 1
0
        public static List <T> ReaderToObjectList <T>(DbDataReader reader)
        {
            if (!reader.HasRows)
            {
                return(new List <T>());
            }
            var      type  = typeof(T);
            List <T> list  = new List <T>();
            var      first = true;

            Tuple <PropertyInfo, Delegate>[] tupleArr = new Tuple <PropertyInfo, Delegate> [reader.FieldCount];
            string[] nameArr = new string[reader.FieldCount];

            while (reader.Read())
            {
                T obj = Activator.CreateInstance <T>();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    Tuple <PropertyInfo, Delegate> tuple = null;
                    string fieldName = null;
                    if (first)
                    {
                        tuple       = ReflectionCache.GetCachedPP <T>(type, fieldName);
                        tupleArr[i] = tuple;
                        fieldName   = reader.GetName(i);
                        nameArr[i]  = fieldName;
                    }
                    else
                    {
                        tuple     = tupleArr[i];
                        fieldName = nameArr[i];
                    }
                    if (tuple != null)
                    {
                        var value = reader.GetValue(i);
                        if (value == null || value is DBNull)
                        {
                            continue;
                        }
                        SetPropertyValue(tuple, type, obj, fieldName, value);
                    }
                }
                list.Add(obj);
                first = false;
            }

            return(list);
        }
Exemplo n.º 2
0
 /// <summary>
 /// 用reader填充T类型的对象,并返回
 /// </summary>
 /// <typeparam name="T">类型参数</typeparam>
 /// <param name="reader">dataReader</param>
 /// <returns></returns>
 public static T ReaderToObject <T>(DbDataReader reader)
 {
     if (reader.Read())
     {
         T   obj  = Activator.CreateInstance <T>();
         var type = typeof(T);
         for (int i = 0; i < reader.FieldCount; i++)
         {
             var tuple = ReflectionCache.GetCachedPP <T>(type, reader.GetName(i));
             SetPropertyValue(tuple, type, obj, reader.GetName(i), reader.GetValue(i));
         }
         return(obj);
     }
     else
     {
         return(default(T));
     }
 }