Yesterday, I was told that to convert a datareader object into an object, I had to write a general method. I think reflection can be used. Projects generally use third-party components for data access layers, such as nhib.pdf and EF. So I want to write a simple example for fun.
In fact, it is easy to implement. A generic method. The Code is as follows:
1 public list <t> tolist <t> (string _ SQL) where T: Class, new () 2 {3 4 using (VAR conn = new sqlconnection (connstr )) 5 {6 using (VAR comm = new sqlcommand (_ SQL, Conn) 7 {8 Conn. open (); 9 sqldatareader datareader = comm. executereader (); 10 if (datareader. hasrows) 11 {12 list <t> datalist = new list <t> (); 13 14 While (datareader. read () 15 {16 t OBJ = new T (); 17 // obtain all attributes of a generic object 18 var properties = obj. getType (). getproperties (); 19 foreach (VAR property in properties) 20 {21 for (INT I = 0; I <datareader. fieldcount; I ++) 22 {23 // query the 24 if (datareader. getname (I ). equals (property. name, stringcomparison. currentcultureignorecase) 25 {26 // assign 27 property to the property of the newly created OBJ object. setvalue (OBJ, datareader [I]); 28} 29} 30} 31 datalist. add (OBJ); 32} 33 Conn. close (); 34 return datalist; 35} 36 37} 38} 39 return NULL; 40}View code
Full code link: http://download.csdn.net/detail/ybealq/7767735