. NET schema base method-datatabletolist Common method we often need to return the data read from the database as a DataTable type, and often need to traverse the DataTable to convert to list>t<. It is also often necessary to convert each DataTable to a list individually and to write a method that fits their database schema. The following code:
Public Static classDatatabletools<t>whereT:class,New() { Public StaticList<t>datatabletolist (DataTable dt) {List<T> list =NULL; varRowCount =dt. Rows.Count; if(RowCount >0) {List=NewList<t>(); inti; for(i =0; i < RowCount; i++) {T model=Datarowtomodel (dt. Rows[i]); List. ADD (model); } } returnlist; } Private StaticT Datarowtomodel (DataRow DR) {T model=NewT (); varPropertiescount =typeof(T). GetProperties (). Length; for(intj =0; J < Propertiescount; J + +) {PropertyInfo PropertyInfo=Getmodelpropertyinfo (model, Dr. TABLE.COLUMNS[J]); if(PropertyInfo! =NULL&& Dr[j]! =dbnull.value) {propertyinfo.setvalue (model, dr[j]); } } returnmodel; } Private StaticPropertyInfo Getmodelpropertyinfo (T model, DataColumn column) {stringPropertyName =column. ColumnName; returnmodel. GetType (). GetProperty (PropertyName); } }
It is also necessary to traverse the DataTable in the code to convert each line in the DataTable to a model of type T first. Here, we get the columnname of each column of the row based on the data schema for each row of data. It is precisely this columnname that we get the property-getmodelpropertyinfo () method of the generic T, in which the property value of the model is set by SetValue. It is also the name of the column property that uses the row data schema to get the properties of the generic T.
Therefore, it is important to ensure that the property name and data schema name of the generic T are the same, and only in this way can the common method be used. It is believed that Daniel has already mastered such a method, if there is any proposal to welcome the point. If you have learned, please praise for yourself, also for my praise.
. NET infrastructure Approach-datatabletolist common approach