日期:2010-12-02  浏览次数:20527 次

呃```花了一晚上时间,终于搞出来了如何通过反射,从DataReader将数据填充到数据实体泛型集合的静态方法.

//Kchen.Core.BaseBusinessObject为通用数据实体类,此处仅为限定T所继承的类型
        public static IList<T> FillDataListGeneric<T>(System.Data.IDataReader reader) where T : Kchen.Core.BaseBusinessObject
        {
            //实例化一个List<>泛型集合
            IList<T> DataList = new List<T>();
            while (reader.Read())
            {
                //由于是是未知的类型,所以必须通过Activator.CreateInstance<T>()方法来依据T的类型动态创建数据实体对象
                T RowInstance = Activator.CreateInstance<T>();
                //通过反射取得对象所有的Property
                foreach (PropertyInfo Property in typeof(T).GetProperties())
                {
                    //BindingFieldAttribute为自定义的Attribute,用于与数据库字段进行绑定
                    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);
                            }
                        }
                      &nbs