利用c#反射實現實體類生成以及數據獲取與賦值


轉:http://hi.baidu.com/xyd21c/item/391da2fc8fb351c10dd1c8b8

原有的實體類成員逐個賦值與獲取的方法弊端:

1、每次對實體類屬性進行賦值時,都要檢查reader的值是否為DBNull,出現了很多重復代碼

2、每次對實體類屬性進行賦值時,都要進行類型轉換, 而實體類屬性的類型是已知的,是不是可以自動完成這樣的轉換?

3、每次對實體類屬性進行賦值時,都要進行實體類屬性與數據庫字段的對應。如果我們在設計數據庫與實體類時,保證數據庫字段與實體類屬性采用同樣的名稱,那利用反射,我們可以通過代碼自動進行屬性與字段的對應。即使數據庫字段與屬性不同名,我們也可以通過更改查詢語句,來做到這一點。

改進后的方法:

private void ReaderToObject(IDataReader reader, object targetObj)
         {
             for (int i = 0; i < 5; i++)
             {
                 System.Reflection.PropertyInfo propertyInfo = targetObj.GetType().GetProperty(reader.GetName(i));
                 if (propertyInfo != null)
                 {
                     if (reader.GetValue(i) != DBNull.Value)
                     {
                         if (propertyInfo.PropertyType.IsEnum)
                         {
                             propertyInfo.SetValue(targetObj, Enum.ToObject(propertyInfo.PropertyType, reader.GetValue(i)), null);
                         }
                         else
                         {
                             propertyInfo.SetValue(targetObj, reader.GetValue(i), null);
                         }
                     }
                 }
             }
         }
     }

來源鏈接

更完善的方法:

public static IList<T> FillList<T>(System.Data.IDataReader reader)
         {
             IList<T> lst = new List<T>();
             while (reader.Read())
             {
                 T RowInstance = Activator.CreateInstance<T>();
                 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)
                             {
                                 Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);
                             }
                         }
                         catch
                         {
                             break;
                         }
                     }
                 }
                 lst.Add(RowInstance);
             }
             return lst;
         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM