Object Class and DataTable conversion, object datatable Conversion
Introduction
Recently, the time spent in database query in the project always needs to use the conversion from a data table to a list of Object-class objects. It encapsulates a conversion method and is easy to use, in the future, we can reuse it. The principle is mainly to use reflection. Of course, there is a better ORM framework for implementation. The main reason is that I didn't use orm here.
Implementation
The code is directly implemented.
/// <Summary> /// data table conversion class /// </summary> /// <typeparam name = "T"> </typeparam> public class DbTableConvertor <T> where T: new () {// <summary> // converts a DataTable to an object list /// Author: oldman // Creation Time: september 13, 2015 /// </summary> /// <param name = "dt"> DataTable to be converted </param> /// <returns> </returns> public List <t> ConvertToList (DataTable dt) {// define the set var list = new List <T> (); if (0 = dt. rows. count) {return list ;} // Traverse all data rows in the DataTable foreach (DataRow dr in dt. rows) {var entity = new T (); // obtain the public attribute var propertys = entity of this model. getType (). getProperties (); // traverses all attributes of the object. foreach (var p in propertys) {// assign the attribute name to the Temporary Variable string tmpName = p. name; // check whether the DataTable contains this column (column Name = Object attribute Name) if (dt. columns. contains (tmpName) {// determines whether this property has a Setter if (! P. canWrite) {continue; // This attribute cannot be written, jump out directly} // value var value = dr [tmpName]; // if not empty, the property if (value! = DBNull. value) {p. setValue (entity, value, null) ;}// Add the object to the list in the generic set. add (entity) ;}return list ;}/// <summary> /// convert the first line of the DataTable to the object /// Author: oldman /// Creation Time: september 13, 2015 /// </summary> /// <param name = "dt"> DataTable to be converted </param> /// <returns> </returns> public T ConvertToEntity (DataTable dt) {var entity = new T (); if (0 = dt. rows. count) {return entity;} // obtain the public attribute var propertys = entit of this model Y. getType (). getProperties (); // traverses all attributes of the object. foreach (var p in propertys) {// assign the attribute name to the Temporary Variable string tmpName = p. name; // check whether the DataTable contains this column (column Name = Object attribute Name) if (dt. columns. contains (tmpName) {// determines whether this property has a Setter if (! P. canWrite) {continue; // This attribute cannot be written, jump out directly} // value var value = dt. rows [0] [tmpName]; // if it is not empty, the property if (value! = DBNull. Value) {p. SetValue (entity, value, null) ;}} return entity ;}}
All the comments are clear. Please click it.
My. NET technology exchange group: 226704167
Studying hard is just a dream.