1 each time the data read the database is a DataTable table, before is silly each table write a converted class, and later to study a generic method, for all conversions
/// <summary> ///Returns a collection/// </summary> /// <typeparam name= "T2" >entity to pass in</typeparam> /// <param name= "strSQL" >SQL statement or stored procedure type</param> /// <param name= "Sqlcomtype" >SQL statement or stored procedure type</param> /// <param name= "pars" >SQL parameter Array</param> /// <returns></returns> Public StaticList<t2> excutelist<t2> (stringstrSQL, CommandType Sqlcomtype,ref stringErrMsg,paramssqlparameter[] pars) { Try { using(SqlConnection conn =NewSqlConnection (s_connectionstring)) {SqlDataAdapter SDA=NewSqlDataAdapter (strSQL, Conn); if(Pars! =NULL) {SDA. SelectCommand.Parameters.AddRange (pars); } Sda.SelectCommand.CommandType=Sqlcomtype; DataTable DT=NewDataTable (); Sda. Fill (DT); if(dt. Rows.Count >0) {List<T2> list =NewList<t2>(); Type T=typeof(T2); foreach(DataRow Drinchdt. Rows) {T2 model=(T2) activator.createinstance (t); Propertyinfo[] Pros=t.getproperties (); foreach(PropertyInfo Pinchpros) { stringColName =P.name; if(dt. Columns.contains (colname)) {if(P.canwrite = =false)Continue; ObjectCellvalue =Dr[colname]; if(Cellvalue! =dbnull.value) {p.setvalue (model, Cellvalue, NULL); }}} list. ADD (model); } returnlist; } Else { return NULL; } } } Catch(Exception ex) {errmsg=Ex. ToString (); return NULL; } }
Call
Public ilist<c_accountmodel> getaccountlist (ref string errmsg) { return c_sqlhelper.excutelist<c_ Accountmodel> ("SELECT * from Account ORDER by ID Desc", CommandType.Text, ref errmsg, NULL); }
2 Places of attention
A: The fields of a database table must be the same as the entity or it cannot be loaded when reflected.
To read data from a database table and turn it into a corresponding entity generic method