DataTable is converted to Model object, datatablemodel
I remember that at school, SqlHelper is the most commonly used. It is the most annoying to convert a DataTable or DataReader to an object every time I read it, because I need to write a lot of code, and it makes no sense. Then I got in touch with the reflection, so I checked the information and wrote a able that had been broken into a Model object.
1 public static IEnumerable <T> DataTableToModels <T> (this DataTable dt) where T: class, new () 2 {3 // determine whether the datatable has a value of 4 if (dt. columns. count <1 | dt. rows. count <1) yield return default (T); 5 // obtain all the public attributes in the object class, in addition, column 6 var propertyInfos = from propertyInfo in typeof (T) exists in the datatable are filtered out ). getProperties () 7 where dt. columns. contains (propertyInfo. name) 8 select propertyInfo; 9 // set attributes 10 foreach (DataRow dr in dt. rows) // traverse all Rows in dt 11 {12 var result = new T (); 13 foreach (var p in propertyInfos) // traverse all properties 14 {15 try16 {17 p. setValue (result, dr [p. name], null); 18} 19 catch (System. exception) 20 {21 22 throw; 23} 24} 25 yield return result; 26} 27 28}
Note that DataTable. Columns. Contains and assign values to a given Name are case-insensitive!