Examples of methods for converting C # DataTable to different struct entity classes

Source: Internet
Author: User
In the actual development process, or a third-party company to provide data table structure, and our system in the Entity class field does not correspond to, encountered so how do we deal with it? One might say that creating an entity object at the time of conversion, the data in the table is instantiated on a row-by-line basis, the entity object is not finished. It is true that this method is feasible, but this method is very inefficient, and it is very efficient to instantiate billions of objects if you encounter billions of data.
Look at my entity class first.

<summary>///specific entity classes, and data tables differ//</summary>public class person{    [DataField ("user_name")]// Represents a field in a database table public    string UserName {set; get;} Represents the field that needs to be converted    [DataField ("Pass_word")] public    string PassWord {set; get;}}

There is a comment in the code, the following is the conversion class

[AttributeUsage (Attributetargets.property)]public sealed class datafieldattribute:attribute{//<summary>/    The field name corresponding to the table///</summary> public string ColumnName {set; get;}    Public Datafieldattribute (String columnName) {columnName = ColumnName; }}public Static class dataconvert<t> where T:new () {///<summary>//Convert DataRow line to entity///&LT;/S ummary>//<param name= "Dr" ></param>///<returns></returns> public static T toentity    (DataRow DR)        {T entity = new T ();        Type info = typeof (T); var members = info.        GetMembers (); foreach (var mi in) {if (MI). MemberType = = Membertypes.property) {//Read properties on DataField attribute object[] attributes = m                I.getcustomattributes (typeof (Datafieldattribute), true); foreach (var attr in attributes) {var datafieldattr = attr as DAtafieldattribute; if (datafieldattr! = null) {var propinfo = info. GetProperty (mi.                        Name); if (Dr. Table.Columns.Contains (Datafieldattr.columnname)) {//According to ColumnName, the The relative field is assigned to the Entity property Propinfo.setvalue (Entity, Convert.                        ChangeType (Dr[datafieldattr.columnname], propinfo.propertytype), NULL);    }}}}} return entity;     }///<summary>//Convert DataTable to Entity List///</summary>//<param name= "DT" ></param>  <returns></returns> public static list<t> ToList (DataTable dt) {list<t> List = new list<t> (dt.        Rows.Count); foreach (DataRow dr in Dt. Rows) {list. Add(Toentity (DR));    } return list; }}

Calling code:

DataTable dt = new DataTable ();d T. Columns.Add ("user_name");d T. Columns.Add ("Pass_word");//This is the field in the table, now you need to convert them to a specific entity class instance dt. Rows.Add ("Kingtiger", "1");d T. Rows.Add ("Wangbiao", "2"); var users = Dataconvert<person>. ToList (DT); foreach (var user in users) {    Response.Write (user. UserName + "," + user. PassWord);} for (int i = 0; i < dt. Rows.Count; i++) {person    p = dataconvert<person>. toentity (dt. Rows[i]);    Response.Write (P.username + "," + P.password);}
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.