DataTable data is assigned to the Model generic method. datatablemodel

Source: Internet
Author: User

DataTable data is assigned to the Model generic method. datatablemodel

I believe that during project creation, different models are often created based on different tables. When the Model needs to be instantiated, the data is first retrieved from the database, assign each value of the data to a model. If you have 10 models, each time you get data from different tables, the data to be processed is completely different, write 10 methods and assign values to 10 models. Low coding efficiency. To improve code versatility, a general method is provided to implement datatable value assignment model.

Table Structure(For demonstration purposes only, the column attribute in the table is not set. The default value is null ):

CREATE TABLE [AddressInfo](    [Name] [NVARCHAR](20) NULL,    [Sex] [NVARCHAR](2) NULL,    [Address] [NVARCHAR](50) NULL,    [Age] [INT] NULL,    [Birthday] [DATE] NULL) 

Model class:

1 public class AddressInfoModel 2 {3 4 // <summary> 5 // Name 6 /// </summary> 7 public string Name {get; set ;} 8 /// <summary> 9 /// gender 10 /// </summary> 11 public string Sex {get; set ;} 12 /// <summary> 13 /// Address 14 /// </summary> 15 public string Address {get; set ;} 16 /// <summary> 17 /// age 18 /// </summary> 19 public int? Age {get; set;} 20 /// <summary> 21 /// birthday 22 /// </summary> 23 public DateTime? Birthday {get; set;} 24 25}

We usually obtain the Model object in this way.:

1 /// <summary> 2 /// get an object 3 /// </summary> 4 public AddressInfo DataRowToModel (DataRow row) 5 {6 Maticsoft. model. addressinfo model = new Maticsoft. model. addressinfo (); 7 if (row! = Null) 8 {9 if (row ["id"]! = Null & row ["id"]. ToString ()! = "") 10 {11 model. id = int. Parse (row ["id"]. ToString (); 12} 13 if (row ["name"]! = Null) 14 {15 model. name = row ["name"]. ToString (); 16} 17 if (row ["Sex"]! = Null) 18 {19 model. Sex = row ["Sex"]. ToString (); 20} 21 if (row ["Address"]! = Null) 22 {23 model. Address = row ["Address"]. ToString (); 24} 25 if (row ["Age"]! = Null & row ["Age"]. ToString ()! = "") 26 {27 model. Age = int. Parse (row ["Age"]. ToString (); 28} 29 if (row ["Birthday"]! = Null & row ["Birthday"]. ToString ()! = "") 30 {31 model. Birthday = DateTime. Parse (row ["Birthday"]. ToString (); 32} 33} 34 return model; 35} 36

I believe this is a common method. The advantage of this method is that it is simple and easy to understand. However, there is a drawback in writing this method, that is, the versatility of the method is very poor, and there is no universality at all, it is not easy to maintain in the future.

Imagine:

(1) If we have 100 models that need to be assigned a value, do we need to write 100 such methods to assign a value to the Model?

(2) once the Model attribute changes, the corresponding method must also be modified accordingly. If the customer constantly proposes to modify the Model attribute, isn't the workload heavy?

Oh, my God! This workload is unimaginable.

Through the above thinking, we can easily find that no matter how many models are actually assigning values to them, the logic processing is a regular and repetitive job, assign the columns in DataRow to the corresponding Model attribute.

After some efforts, the first version of the general method was finally released (not to mention nonsense, just do it !)

(1) version 1 of the General DataRow value assignment Model method: (this method is obsolete and only provides ideas for everyone)

1 /// <summary> 2 /// assign the data in DataRow to the attribute with the same name in the model. 3 /// </summary> 4 /// <typeparam name = "T"> generic: model type </typeparam> 5 // <param name = "objmodel"> instance of model </param> 6 /// <param name = "dtRow"> DataRow </param> 7 public T TableToModel <T> (T objmodel, dataRow dtRow) 8 {9 // obtain the model Type 10 Type modelType = typeof (T); 11 // obtain the attribute 12 PropertyInfo [] modelpropertys = modelType in the model. getProperties (); 13 // traverse each column of the DataTable 14 // traverse every attribute of the model 15 foreach (PropertyInfo pi in modelpropertys) 16 {17 // get attribute name 18 String name = pi. name; 19 // assign the data in DataRow to the attribute with the same name in the model (the case-insensitive attribute Name works the same as the Name) 20 if (dtRow. table. columns. contains (name) 21 {22 object value = dtRow [name]. toString (); 23 pi. setValue (objmodel, value, null); 24} 25} 26}

Tests show that this method is of the string type for Model attributes. In this Model, Age is of the Int type, and Birthday is of the DateTime type. An error of Type mismatch may occur, therefore, the versatility is very poor.On this basis, General Version 2 is introduced.

(2) version 2 of the General DataRow value assignment Model method: (this method is obsolete and only provides ideas for everyone)

Set 22 lines of code
22 object value = dtRow [name]. ToString ();
Change
Object value = Convert. ChangeType (dtRow [name], modelType. GetProperty (name). PropertyType );
The DataRow type does not match the Model type.

At this point, this method is quite versatile and I am very happy. However, in the test, when the database's self-read permission is null, this method cannot adapt to the complicated and changing Model assignment. For example, the age and birthdate fields in this class are allowed to be empty.
Int? Age and DateTime? Birthday will report an error and the null value cannot be assigned to the specified data type, because the method is further improved. The final version is as follows:

(3) final version of the general method of DataRow value assignment Model:
1 /// <summary> 2 /// assign the DataRow value to the attribute with the same name in the model. 3 /// </summary> 4 /// <typeparam name = "T"> wildcard type: model type </typeparam> 5 // <param name = "objmodel"> model instance </param> 6 /// <param name = "dtRow"> able row data </param> 7 public T TableRowToModel <T> (T objmodel, dataRow dtRow) 8 {9 // obtain the model Type 10 Type modelType = typeof (T); 11 // obtain the attribute 12 PropertyInfo [] modelpropertys = modelType in the model. getProperties (); 13 // traverse each attribute of the model And assign a value to the column 14 foreach (PropertyInfo pi in modelpropertys) corresponding to DataRow 15 {16 // get the attribute name 17 String name = pi. name; 18 if (dtRow. table. columns. contains (name) 19 {20 // non-generic 21 if (! Pi. PropertyType. IsGenericType) 22 {23 pi. SetValue (objmodel, string. IsNullOrEmpty (dtRow [name]. ToString ())? Null: Convert. changeType (dtRow [name], pi. propertyType), null); 24} 25 // generic Nullable <> 26 else27 {28 Type genericTypeDefinition = pi. propertyType. getGenericTypeDefinition (); 29 // The model attribute can be of the null type, with a null value of 30 if (genericTypeDefinition = typeof (Nullable <> )) 31 {32 // return the basic type parameter 33 pi of the specified type that can be null. setValue (objmodel, string. isNullOrEmpty (dtRow [name]. toString ())? Null: Convert. ChangeType (dtRow [name], Nullable. GetUnderlyingType (pi. PropertyType), null); 34} 35} 36} 37} 38 return objmodel; 39}
 
Finally, the DataRow data is assigned to the Model.

This method can be used to assign a DataTable value to List <Model> !! (This will not be demonstrated here)


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.