你的位置:首页 > ASP.net教程

[ASP.net教程]利用反射把查询到的Table、Reader转换成List、Model


 

菜鸟一枚,入园已有两年三个月,这还是第一次写博客,请各位大神斧正。

 

这是我写的一个工具类,通常我们从数据库查询到一个  DataReader  或者是  一个 Table , 想要转换成 一个 list 或者是 一个model 的话 , 一般情况下是使用foreach 循环reader或是tablerows,然后在循环内创建个对象,通过reader[“列名”]来赋值对象的属性。如果表的字段少的话,用这种方式还可以,速度也快一点。但是如果后续还会增加字段的话,那就非常麻烦了,要改很多地方。这工作量太大了,而且还很容易出错。所以这个时候使用反射来转换的话就非常便捷了。我们只管增加字段,改一下数据表对应的model,调用这个工具类的方法,传入相对应的参数就能得到想要的结果。

 

诶,文笔不好,直接上代码吧。

 1 /// <summary> 2     /// table转list 3     /// </summary> 4     /// <typeparam name="T">list类型</typeparam> 5     /// <param name="obj">model对象</param> 6     /// <param name="table">数据源table</param> 7     /// <returns>list</returns> 8     public static List<T> FillListByDataTable<T>(T obj, DataTable table) 9     { 10  11       Type type = obj.GetType(); 12  13       List<T> list = new List<T>(); 14  15       PropertyInfo[] properties = type.GetProperties();//model对象的属性集合 16  17       DataColumnCollection dcc = table.Columns;//列集合 18  19       foreach (DataRow row in table.Rows) 20       { 21         //复制一个model对象(深拷贝) 22         MemoryStream stream = new MemoryStream(); 23         BinaryFormatter formatter = new BinaryFormatter(); 24         formatter.Serialize(stream, obj); 25         stream.Position = 0; 26         T newObj = (T)formatter.Deserialize(stream); 27  28         foreach (PropertyInfo p in properties) 29         { 30           Type t = p.PropertyType; 31  32           if (dcc.Contains(p.Name.ToString())) 33           { 34             if (!string.IsNullOrEmpty(row[p.Name].ToString())) 35             { 36               //判断字段类型 37               if (t.Name != "Nullable`1") 38               { 39                 p.SetValue(newObj, Convert.ChangeType(row[p.Name], t, null)); 40               } 41               else if (t.FullName == "System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") 42               { 43                 p.SetValue(newObj, Convert.ChangeType(row[p.Name], typeof(DateTime), null)); 44               } 45               else if (t.FullName == "System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") 46               { 47                 p.SetValue(newObj, Convert.ChangeType(row[p.Name], typeof(DateTime), null)); 48               } 49               else if (t.FullName == "System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") 50               { 51                 p.SetValue(newObj, Convert.ChangeType(row[p.Name], typeof(Int32), null)); 52               } 53               else if (t.FullName == "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") 54               { 55                 p.SetValue(newObj, Convert.ChangeType(row[p.Name], typeof(Int32), null)); 56               } 57               else if (t.FullName == "System.Nullable`1[[System.Int64, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") 58               { 59                 p.SetValue(newObj, Convert.ChangeType(row[p.Name], typeof(Int64), null)); 60               } 61               else if (t.FullName == "System.Nullable`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") 62               { 63                 p.SetValue(newObj, Convert.ChangeType(row[p.Name], typeof(Int64), null)); 64               } 65               else if (t.FullName == "System.Nullable`1[[System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") 66               { 67                 p.SetValue(newObj, Convert.ChangeType(row[p.Name], typeof(Decimal), null)); 68               } 69               else if (t.FullName == "System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") 70               { 71                 p.SetValue(newObj, Convert.ChangeType(row[p.Name], typeof(Decimal), null)); 72               } 73               else if (t.FullName == "System.Nullable`1[[System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") 74               { 75                 p.SetValue(newObj, Convert.ChangeType(row[p.Name], typeof(Boolean), null)); 76               } 77               else if (t.FullName == "System.Nullable`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") 78               { 79                 p.SetValue(newObj, Convert.ChangeType(row[p.Name], typeof(Boolean), null)); 80               } 81             } 82  83           } 84         } 85         list.Add(newObj); 86       } 87       return list; 88     } 89  90     /// <summary> 91     /// reader转list 92     /// </summary> 93     /// <typeparam name="T">list类型</typeparam> 94     /// <param name="obj">model对象</param> 95     /// <param name="reader">数据源reader</param> 96     /// <returns>list </returns> 97     public static List<T> FillListByDataReader<T>(T obj ,IDataReader reader) 98     { 99       List<T> list = new List<T>();100 101       Type t = obj.GetType();102 103       PropertyInfo[] proList = t.GetProperties();104 105       while(reader.Read())106       {107         MemoryStream stream = new MemoryStream();108         BinaryFormatter formatter = new BinaryFormatter();109         formatter.Serialize(stream, obj);110         stream.Position = 0;111         T newObj = (T)formatter.Deserialize(stream);112 113         foreach (PropertyInfo pro in proList)114         {115           Type tp = pro.PropertyType;116 117           DataFieldAttribute attr = pro.GetCustomAttributes().Count() > 0 ? pro.GetCustomAttributes().First() as DataFieldAttribute : null;118 119           if (attr != null && attr.ColumnName == pro.Name)120           {121             if (ReaderExists(reader, pro.Name) && !string.IsNullOrEmpty(reader[pro.Name].ToString()))122             {123 124               if (tp.Name != "Nullable`1")125               {126                 pro.SetValue(newObj, Convert.ChangeType(reader[pro.Name], tp));127               }128               else if (tp.FullName == "System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")129               {130                 pro.SetValue(newObj, Convert.ChangeType(reader[pro.Name], typeof(DateTime), null));131               }132               else if (tp.FullName == "System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")133               {134                 pro.SetValue(newObj, Convert.ChangeType(reader[pro.Name], typeof(DateTime), null));135               }136               else if (tp.FullName == "System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")137               {138                 pro.SetValue(newObj, Convert.ChangeType(reader[pro.Name], typeof(Int32), null));139               }140               else if (tp.FullName == "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")141               {142                 pro.SetValue(newObj, Convert.ChangeType(reader[pro.Name], typeof(Int32), null));143               }144               else if (tp.FullName == "System.Nullable`1[[System.Int64, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")145               {146                 pro.SetValue(newObj, Convert.ChangeType(reader[pro.Name], typeof(Int64), null));147               }148               else if (tp.FullName == "System.Nullable`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")149               {150                 pro.SetValue(newObj, Convert.ChangeType(reader[pro.Name], typeof(Int64), null));151               }152               else if (tp.FullName == "System.Nullable`1[[System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")153               {154                 pro.SetValue(newObj, Convert.ChangeType(reader[pro.Name], typeof(Decimal), null));155               }156               else if (tp.FullName == "System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")157               {158                 pro.SetValue(newObj, Convert.ChangeType(reader[pro.Name], typeof(Decimal), null));159               }160               else if (tp.FullName == "System.Nullable`1[[System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")161               {162                 pro.SetValue(newObj, Convert.ChangeType(reader[pro.Name], typeof(Boolean), null));163               }164               else if (tp.FullName == "System.Nullable`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")165               {166                 pro.SetValue(newObj, Convert.ChangeType(reader[pro.Name], typeof(Boolean), null));167               }168             }169           }170         }171         list.Add(newObj);172       }173 174       return list;175     }176 177     /// <summary>178     /// reader转model对象179     /// </summary>180     /// <typeparam name="T">类型</typeparam>181     /// <param name="obj">model对象</param>182     /// <param name="reader">数据源reader</param>183     /// <returns>model对象</returns>184     public static T FillObjectByDataReader<T>(T obj, IDataReader reader)185     {186       Type t = obj.GetType();187 188       PropertyInfo[] proList = t.GetProperties();189 190       if (reader.Read())191       {192         foreach (PropertyInfo pro in proList)193         {194           Type tp = pro.PropertyType;195 196           DataFieldAttribute attr = pro.GetCustomAttributes().Count() > 0 ? pro.GetCustomAttributes().First() as DataFieldAttribute : null;197 198           if (attr != null && attr.ColumnName == pro.Name)199           {200             if (ReaderExists(reader, pro.Name) && !string.IsNullOrEmpty(reader[pro.Name].ToString()))201             {202               if (tp.Name != "Nullable`1")203               {204                 pro.SetValue(obj, Convert.ChangeType(reader[pro.Name], tp));205               }206               else if (tp.FullName == "System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")207               {208                 pro.SetValue(obj, Convert.ChangeType(reader[pro.Name], typeof(DateTime), null));209               }210               else if (tp.FullName == "System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")211               {212                 pro.SetValue(obj, Convert.ChangeType(reader[pro.Name], typeof(DateTime), null));213               }214               else if (tp.FullName == "System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")215               {216                 pro.SetValue(obj, Convert.ChangeType(reader[pro.Name], typeof(Int32), null));217               }218               else if (tp.FullName == "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")219               {220                 pro.SetValue(obj, Convert.ChangeType(reader[pro.Name], typeof(Int32), null));221               }222               else if (tp.FullName == "System.Nullable`1[[System.Int64, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")223               {224                 pro.SetValue(obj, Convert.ChangeType(reader[pro.Name], typeof(Int64), null));225               }226               else if (tp.FullName == "System.Nullable`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")227               {228                 pro.SetValue(obj, Convert.ChangeType(reader[pro.Name], typeof(Int64), null));229               }230               else if (tp.FullName == "System.Nullable`1[[System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")231               {232                 pro.SetValue(obj, Convert.ChangeType(reader[pro.Name], typeof(Decimal), null));233               }234               else if (tp.FullName == "System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")235               {236                 pro.SetValue(obj, Convert.ChangeType(reader[pro.Name], typeof(Decimal), null));237               }238               else if (tp.FullName == "System.Nullable`1[[System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")239               {240                 pro.SetValue(obj, Convert.ChangeType(reader[pro.Name], typeof(Boolean), null));241               }242               else if (tp.FullName == "System.Nullable`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")243               {244                 pro.SetValue(obj, Convert.ChangeType(reader[pro.Name], typeof(Boolean), null));245               }246             }247           }248         }249       }250 251       return obj;252     }253 254     /// <summary>255     /// row转model对象256     /// </summary>257     /// <typeparam name="T">model类型</typeparam>258     /// <param name="obj">model对象</param>259     /// <param name="row">数据源row</param>260     /// <returns>model对象</returns>261     public static T FillObjectByDataTable<T>(T obj, DataRow row)262     {263       Type t = obj.GetType();264 265       PropertyInfo[] proList = t.GetProperties();266 267       foreach (PropertyInfo pro in proList)268       {269         Type tp = pro.PropertyType;270 271         DataFieldAttribute attr = pro.GetCustomAttributes().Count() > 0 ? pro.GetCustomAttributes().First() as DataFieldAttribute : null;272 273         if (attr != null && attr.ColumnName == pro.Name)274         {275           if (!string.IsNullOrEmpty(row[pro.Name].ToString()))276           {277             if (tp.Name != "Nullable`1")278             {279               pro.SetValue(obj, Convert.ChangeType(row[pro.Name], tp, null));280             }281             else if (tp.FullName == "System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")282             {283               pro.SetValue(obj, Convert.ChangeType(row[pro.Name], typeof(DateTime), null));284             }285             else if (tp.FullName == "System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")286             {287               pro.SetValue(obj, Convert.ChangeType(row[pro.Name], typeof(DateTime), null));288             }289             else if (tp.FullName == "System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")290             {291               pro.SetValue(obj, Convert.ChangeType(row[pro.Name], typeof(Int32), null));292             }293             else if (tp.FullName == "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")294             {295               pro.SetValue(obj, Convert.ChangeType(row[pro.Name], typeof(Int32), null));296             }297             else if (tp.FullName == "System.Nullable`1[[System.Int64, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")298             {299               pro.SetValue(obj, Convert.ChangeType(row[pro.Name], typeof(Int64), null));300             }301             else if (tp.FullName == "System.Nullable`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")302             {303               pro.SetValue(obj, Convert.ChangeType(row[pro.Name], typeof(Int64), null));304             }305             else if (tp.FullName == "System.Nullable`1[[System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")306             {307               pro.SetValue(obj, Convert.ChangeType(row[pro.Name], typeof(Decimal), null));308             }309             else if (tp.FullName == "System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")310             {311               pro.SetValue(obj, Convert.ChangeType(row[pro.Name], typeof(Decimal), null));312             }313             else if (tp.FullName == "System.Nullable`1[[System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")314             {315               pro.SetValue(obj, Convert.ChangeType(row[pro.Name], typeof(Boolean), null));316             }317             else if (tp.FullName == "System.Nullable`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")318             {319               pro.SetValue(obj, Convert.ChangeType(row[pro.Name], typeof(Boolean), null));320             }321           }322 323         }324       }325 326 327       return obj;328     }329 330     /// <summary>331     /// list转table332     /// </summary>333     /// <typeparam name="T">list类型</typeparam>334     /// <param name="list">数据源list</param>335     /// <param name="table">table</param>336     /// <returns>table</returns>337     public static DataTable FillDataTableByObject<T>(List<T> list , DataTable table)338     {339       if (list.Count > 0)340       {341         Type type = list[0].GetType();342 343         PropertyInfo[] properties = type.GetProperties();344 345         DataColumnCollection dcc = table.Columns;346 347         foreach (var obj in list)348         {349           DataRow row = table.NewRow();350           foreach (PropertyInfo p in properties)351           {352             if (dcc.Contains(p.Name.ToString()))353             {354               row[p.Name] = p.GetValue(obj);355             }356           }357           table.Rows.Add(row);358         }359       }360       return table;361     }362 363     /// <summary>364     /// 验证reader是否存在某列365     /// </summary>366     /// <param name="reader"></param>367     /// <param name="columnName"></param>368     /// <returns></returns>369     private static bool ReaderExists(IDataReader reader,string columnName)370     {371       int count = reader.FieldCount;372       for(int i = 0; i < count; i++)373       {374         if(reader.GetName(i).Equals(columnName))375         {376           return true;377         }378       }379       return false;380     }

View Code