DataTable is converted to Model object, datatablemodel

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.