How to assign the data in a DataTable to the model simply and flexibly

Source: Internet
Author: User

In a recent project, there are 13 methods that require the same treatment: A SQL statement that takes a specified piece of data from the database, assigns each value in the data to a model, and then sends the data in the model out of the way. Each method takes data from a different table, and the data that needs to be processed is completely different, so it also corresponds to 13 different model. Each property name in these model is given and needs to be post and sent using the given template, so the name of each property must match the provided template.

Here's a simple example to illustrate the current situation:

One of the table structures used in SQL Server to hold data is the following (the actual field has more than 10):

Create Table MemberInfo (    member_id          int,    member_name        varchar(20  ),    member_birthday    varchar(    )go

One of the parameters that needs to be passed to the message template is the following model:

    /// <summary>    ///parameters in the message/// </summary>     Public classWechatouputpara {PrivateString _name =""; /// <summary>        ///member name/// </summary>         PublicString Name {Get{return_name;} Set{_name =value;} }        PrivateString _birthday=""; /// <summary>        ///member Birthday/// </summary>         PublicString Birthday {Get{return_birthday;} Set{_birthday=value;} }    }

The final effect that needs to be achieved: obtain a member information from the database MemberInfo table and assign the name member_name to the Wechatouputpara class. The Name property, which assigns the birthday Member_birthday to the birthday property.

Since there are many methods that need to be handled in the same way, it is natural to think that there is a common way to do it once and for all. After all, the structure of each table is different, the data returned may be as many as more than 10 more than 20 fields, if each method, in order to assign the value of each field in the table to the corresponding property in the model, then the amount of work and code will be very large.

My solution is as follows:

(1) When fetching data from a table through an SQL statement, each field is converted to the same name as the corresponding property in the model.

(2) Write a method that assigns each field in a DataTable table to the same property as its name in the model.

(3) Using generics, this method is used as a common method, which can be called when each data table assigns a value to the corresponding model.

Next, still use the simple examples listed above to illustrate the final solution.

(1) Use the SQL statement to get the data:

Select  as [name]  as  from where = 1

In the code, the obtained data is stored in the DataTable Dtinfo.

(2) Write a common method that assigns each field in a DataTable table to the same property as its name in the model.

        /// <summary>        ///assign each column in the DataTable to a property of the same name in the model///only one row of data in a DataTable/// </summary>        /// <typeparam name= "T" >generics: type of model</typeparam>        /// <param name= "Objmodel" >Example of model</param>        /// <param name= "Dtinfo" >DataTable Table</param>         Public voidTabletomodel<t>(T Objmodel, DataTable dtinfo) {//get the type of modelType Modeltype =typeof(T); //get the properties in modelpropertyinfo[] Modelpropertys =modeltype.getproperties (); //iterate through each column of a DataTable             for(Int32 i =0; i < DtInfo.Columns.Count; i++)            {                //iterate through each of the properties of the model                foreach(PropertyInfo PiinchModelpropertys) {String name= Pi. Name;//Get Property name//if the Model property name is the same as the column name in the table                    if(Name = =Dtinfo.columns[i]. ColumnName) {//gets the data for the column in the table                        ObjectValue = dtinfo.rows[0][i].                        ToString (); //assigns the data under the column in the table to the same name property in the modelModeltype.getproperty (name). SetValue (Objmodel, value,NULL); }                }            }        }

(3) Call the common method in the code and assign the data in the DataTable Dtinfo to the Wechatouputpara class.

// Output Parameters New Wechatouputpara (); // assigning member information to an output parameter Tabletomodel<wechatouputpara> (Objwechatouputpara, dtinfo);

Problem solved, 13 similar methods can directly call this common method, you can complete the assignment operation, is not much simpler? And, if the structure of the data table changes, or the message needs to add, delete parameters, only need to modify the SQL statement and the corresponding model, do not need to modify the corresponding assignment statement, very flexible.

How to assign the data in a DataTable to the model simply and flexibly

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.