Well, I spent a whole night and finally figured out a static method on how to fill data from DataReader into a generic collection of data entities through reflection.
//Kchen.Core.BaseBusinessObject is a general data entity class, here it only limits the type inherited by T
public static IList<T> FillDataListGeneric<T>(System.Data.IDataReader reader) where T : Kchen.Core.BaseBusinessObject
{
//Instantiate a List<> generic collection
IList<T> DataList = new List<T>();
while (reader.Read())
{
//Since it is an unknown type, the data entity object must be dynamically created based on the type of T through the Activator.CreateInstance<T>() method.
T RowInstance = Activator.CreateInstance<T>();
//Get all the properties of the object through reflection
foreach (PropertyInfo Property in typeof(T).GetProperties())
{
//BindingFieldAttribute is a custom Attribute used to bind to database fields
foreach (BindingFieldAttribute FieldAttr in Property.GetCustomAttributes(typeof(BindingFieldAttribute), true))
{
try
{
//Get the order of the current database fields
int Ordinal = reader.GetOrdinal(FieldAttr.FieldName);
if (reader.GetValue(Ordinal) != DBNull.Value)
{
//Fill the data read by DataReader into the properties of the object entity
Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);
}
}
catch
{
break;
}
}
}
//Add the data entity object to the generic collection
DataList.Add(RowInstance);
}
return DataList;
}
Use the following code when calling
//Pseudocode OleDbDataReader _ds = Create an OleDbDataReader
IList<Product> _result = Kchen.Utilities.FillDataListGeneric<Product>(_ds);
This static method quickly fills data into the data entity generic collection through an entity type and DateReader.
http://www.cnblogs.com /kchen/archive/2006/10/31/545011.html