zoukankan      html  css  js  c++  java
  • 转: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;
            }

        }
    }

  • 相关阅读:
    POJ 1258 Agri-Net (prim水题)
    POJ 1258 Agri-Net (prim水题)
    Call to your teacher
    Call to your teacher
    Redis 笔记与总结8 PHP + Redis 信息管理系统(分页+好友关注)
    用R语言求置信区间
    用R语言求置信区间
    竞品分析报告正确的打开方式
    竞品分析报告正确的打开方式
    内容分析在用户反馈分析中的应用
  • 原文地址:https://www.cnblogs.com/dudu837/p/1563810.html
Copyright © 2011-2022 走看看