DataReader To List<T>

 public static List<T> GetList<T>(IDataReader dr)
        {
            List<T> entityList = new List<T>();
            int fieldCount = -1;

            while (dr.Read())
            {
                if (fieldCount == -1)
                    fieldCount = dr.FieldCount;

                // 得到实体类对象   
                T t = (T)Activator.CreateInstance(typeof(T));

                for (int i = 0; i < fieldCount; i++)
                {
                    PropertyInfo prop = t.GetType().GetProperty(dr.GetName(i),
                        BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);

                    if (null != prop)
                    {
                        // 为了能用在默认为null的值上   
                        // 如 DateTime? tt = null;   
                        if (null == dr[i] || Convert.IsDBNull(dr[i]))
                            prop.SetValue(t, null, null);
                        else
                            prop.SetValue(t, dr[i], null);
                    }
                }

                entityList.Add(t);
            }
            dr.Close();
            return entityList;
        }

阅读更多
文章标签: list null
个人分类: C#
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭