您的位置:首页 > 其它

转:DataReader填充为List<T>

2009-09-10 09:57 351 查看
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;
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: