This is a common problem in database development, of course, this can be solved with a ready-made ORM framework, but sometimes, if Dataset/datatable is returned by a third-party interface, ORM is inconvenient and has to be handled by itself.
Reflection of nature is essential, in addition, considering that the ColumnName in a DataTable is usually not strictly corresponding to the model's PropertyName, you can use attribute to record this mapping relationship.
Step 1: Create a Datafieldattribute class First
usingSystem;2 3 namespaceJimmy.orm4 { 5[AttributeUsage (attributetargets.property)]6 Public Sealed classDatafieldattribute:attribute7 { 8 /// <summary> 9 ///the field name corresponding to the tableTen /// </summary> One Public stringColumnName {Set;Get; } A - PublicDatafieldattribute (stringcolumnName) - { theColumnName =ColumnName; - } - } -}
Step 2: on the class member of Model/entity, apply the DataField attribute, see the following code:
usingSystem;namespacejimmy.orm.entity{[Serializable] Public classproductentity:dataentitybase {[DataField ("Product_no")] Public stringProductno {Set;Get; } [DataField ("product_id")] Public intProductId {Set;Get; } [DataField ("Product_Name")] Public stringProductName {Set;Get; } Public Override stringToString () {return string. Format ("Productno:{1}{0}productid:{2}{0}productname:{3}", Environment.NewLine, Productno, ProductId, ProductName); } }}
Step 3: The reflection came out, for the sake of convenience, encapsulated a Dataconvert class
usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Reflection;namespacejimmy.orm{/// <summary> ///convert datarow/datatable to entity/entity list/// </summary> Public Static classDataconvert<t>whereT:dataentitybase,New() { /// <summary> ///convert DataRow rows to entity/// </summary> /// <param name= "Dr" ></param> /// <returns></returns> Public StaticT Toentity (DataRow DR) {T entity=NewT (); Type Info=typeof(T); varMembers =info. GetMembers (); foreach(varMiinchMembers ) { if(MI.) MemberType = =membertypes.property) {//the DataField attribute on the Read attribute Object[] attributes = mi. GetCustomAttributes (typeof(Datafieldattribute),true); foreach(varattrinchattributes) { varDatafieldattr = attr asDatafieldattribute; if(Datafieldattr! =NULL) { varPropinfo =info. GetProperty (mi. Name); if(Dr. Table.Columns.Contains (Datafieldattr.columnname)) {//Assign a relative field in DR to the entity property according to ColumnNamePropinfo.setvalue (Entity, Convert.cha Ngetype (Dr[datafieldattr.columnname], propinfo.propertytype),NULL); } } } } } returnentity; } /// <summary> ///convert a DataTable into an entity list/// </summary> /// <param name= "DT" ></param> /// <returns></returns> Public StaticList<t>ToList (DataTable dt) {List<T> list =NewList<t>(dt. Rows.Count); foreach(DataRow Drinchdt. Rows) {list. ADD (Toentity (DR)); } returnlist; } }}
Step 4: test
usingSystem;usingSystem.Data;usingJimmy.ORM.Entity;namespacejimmy.orm.test{classProgram {Static voidMain () {DataTable dt=NewDataTable (); Dt. Columns.Add ("Product_no"); Dt. Columns.Add ("product_id"); Dt. Columns.Add ("Product_Name"); Dt. Rows.Add ("00001",1,"Mobile Phone"); Dt. Rows.Add ("00002",2,"Apparel"); varProducts = dataconvert<productentity>. ToList (DT); foreach(varEntityinchProducts ) {Console.WriteLine (entity); } console.read (); } }}
C #:D atatable map into model