转:DataReader填充为List<T>

using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Workflow.Runtime.Tracking;

namespace Test
{

    //自定义的Attribute,用于与数据库字段进行绑定
    public class BindingFieldAttribute : System.Attribute
    {
        public string FieldName { get; set; }
    }

    //通用实体类
    public class BaseBusinessObject
    {
        //....
    }
    public class Test
    {

        //BaseBusinessObject为通用数据实体类,此处仅为限定T所继承的类型
        public static IList<T> FillDataListGeneric<T>(IDataReader reader) where T : BaseBusinessObject
        {

            //实例化一个List<>泛型集合
            IList<T> DataList = new List<T>();
            while (reader.Read())
            {
                T RowInstance = Activator.CreateInstance<T>();//动态创建数据实体对象

                //通过反射取得对象所有的Property
                foreach (PropertyInfo Property in typeof(T).GetProperties())
                {
                    foreach (BindingFieldAttribute FieldAttr in Property.GetCustomAttributes(typeof(BindingFieldAttribute), true))
                    {
                        try
                        {
                            //取得当前数据库字段的顺序
                            int Ordinal = reader.GetOrdinal(FieldAttr.FieldName);
                            if (reader.GetValue(Ordinal) != DBNull.Value)
                            {
                                //将DataReader读取出来的数据填充到对象实体的属性里
                                Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);
                            }
                        }
                        catch
                        {
                            break;
                        }
                    }
                }
                DataList.Add(RowInstance);
            }
            return DataList;
        }

    }
}

原文地址:https://www.cnblogs.com/dudu837/p/1563810.html