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///</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);}