Introduction
Recently in the project in the database query time, always use the data table to the entity class object list conversion, self encapsulated a conversion method, used to be more convenient, write down, can be reused later, the principle is mainly to use reflection, of course, there is a better ORM framework can be achieved, The main reason is that I don't use ORM here.
Realize
Words not much, directly on the implementation of the Code
/// <summary> ///data Table Conversion classes/// </summary> /// <typeparam name= "T" ></typeparam> Public classDbtableconvertor<t>whereT:New() { /// <summary> ///Convert a DataTable to a list of entities///Author: Oldman///Creation Date: September 13, 2015/// </summary> /// <param name= "DT" >DataTable to convert</param> /// <returns></returns> PublicList<t>converttolist (DataTable dt) {//Defining Collections varList =NewList<t>(); if(0==dt. Rows.Count) {returnlist; } //traverse all data rows in a DataTable foreach(DataRow Drinchdt. Rows) {varentity =NewT (); //get the public properties of this model varPropertys =entity. GetType (). GetProperties (); //Traverse All properties of this object foreach(varPinchpropertys) { //Assigning a property name to a temporary variable stringTmpname =P.name; //Check if DataTable contains this column (column name = = Property Name of object) if(dt. Columns.contains (Tmpname)) {//determine if this property has a setter if(!p.canwrite) { Continue;//This property is not writable and jumps directly out of } //Take value varValue =Dr[tmpname]; //if not NULL, the property assigned to the object if(Value! =dbnull.value) {P.setvalue (entity, Value,NULL); } } } //object is added to the generic collectionlist. ADD (entity); } returnlist; } /// <summary> ///convert the first row of a DataTable to an entity///Author: Oldman///Creation Date: September 13, 2015/// </summary> /// <param name= "DT" >DataTable to convert</param> /// <returns></returns> PublicT converttoentity (DataTable dt) {varentity =NewT (); if(0==dt. Rows.Count) {returnentity; } //get the public properties of this model varPropertys =entity. GetType (). GetProperties (); //Traverse All properties of this object foreach(varPinchpropertys) { //Assigning a property name to a temporary variable stringTmpname =P.name; //Check if DataTable contains this column (column name = = Property Name of object) if(dt. Columns.contains (Tmpname)) {//determine if this property has a setter if(!p.canwrite) { Continue;//This property is not writable and jumps directly out of } //Take value varvalue = dt. rows[0][tmpname]; //if not NULL, the property assigned to the object if(Value! =dbnull.value) {P.setvalue (entity, Value,NULL); } } } returnentity; } }
The comments are very clear, welcome to shoot bricks.
my own. NET Learning Technology Exchange Group: 226704167
study hard, only for a dream.
Transformation of entity classes and DataTable