• 转: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;
            }

        }
    }

  • 相关阅读:
    java_监控工具jvisualvm
    bzoj3667: Rabin-Miller算法
    bzoj3677: [Apio2014]连珠线
    4070: [Apio2015]雅加达的摩天楼
    4069: [Apio2015]巴厘岛的雕塑
    4071: [Apio2015]巴邻旁之桥
    bzoj2653: middle
    1500: [NOI2005]维修数列
    bzoj4262: Sum
    bzoj4540: [Hnoi2016]序列
  • 原文地址:https://www.cnblogs.com/dudu837/p/1563810.html
Copyright © 2020-2023  润新知