集合|靜態
呃```花了一晚上時間,終於搞出來了如何通過反射,從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);
}
}
catch
{
break;
}
}
}
//將資料實體物件add到泛型集合中
DataList.Add(RowInstance);
}
return DataList;
}
調用的時候使用如下代碼
//虛擬碼 OleDbDataReader _ds = 建立一個OleDbDataReader
IList<Product> _result = Kchen.Utilities.FillDataListGeneric<Product>(_ds);
此靜態方法通過一個實體類型和DateReader,快速的將資料填充到資料實體泛型集合中.