The DataTable and object classes written many years ago are converted into datatable entities.

Source: Internet
Author: User

The DataTable and object classes written many years ago are converted into datatable entities.
Introduction

I have been using Ado.net many years ago and gradually transformed to other orm systems. During the transformation process, I intend to combine the two models, use the row status in the DataTable to improve the data control functions in mvc. Now let it go and keep a souvenir.

Cause

Many years ago, I had a deep understanding of Ado.net. At that time, the company also had a set of frameworks that made Ado.net into ORMapping. So I was very skilled in DataTable operations.

The row statuses in the DataTable table are well associated with the latter operations on the interface, such as adding, modifying, canceling, and deleting data, and can all correspond to the row statuses in the DataTable table, then, THE orm framework automatically generates SQL statements based on different row states, which is more convenient.

Later, the technology has been improving, EF has been used, and Nhibernate transplanted from java has been used. As a result, more and more operations are performed on the object class. At that time, this idea was generated, and the interface was bound to the DataTable, then data changes are made persistent through these new orm tools, so this tool class is implemented.

Code

 

Because it is a tool class, the code structure is relatively simple.

The TransformUtil tool class mainly contains three methods.I. ConvertDataTableToModel:This mainly synchronizes the modified content in the DataTable to the object class set.

/// <Summary> /// synchronize the modified content in the DB to the generic set /// </summary> /// <typeparam name = "T"> type </typeparam> /// <param name = "source"> dt source </param> /// <param name = "destinationArray"> Target Model set </param>/ // <returns> </returns> public static bool ConvertDataTableToModel <T> (DataTable source, list <T> destinationArray) where T: class {if (source = null | destinationArray = null | source. primaryKey = null | source. primaryKey. count () <= 0) return false; DataTable dtChange = source. getChanges (); if (dtChange = null) return false; List <string> keys = new List <string> (); foreach (var item in source. primaryKey) {keys. add (item. columnName);} return ConvertDataTableToModel (source, destinationArray, keys );}
II: ConvertDataTableToModel overload:
/// <Summary> /// synchronize the changed data in the table to the generic set (ADD, modify, delete) /// </summary> /// <typeparam name = "T"> type </typeparam> /// <param name = "source"> dt source </param> /// <param name = "destinationArray"> Target Model set </param> /// <param name = "keyColumnArray"> primary key set </param> /// <returns> </returns> public static bool ConvertDataTableToModel <T> (DataTable source, list <T> destinationArray, List <string> keyColumnArray) where T: class {I F (source = null | destinationArray = null | source. rows. count = 0 | keyColumnArray = null | keyColumnArray. count = 0) return false; Type modeType = destinationArray. getType (). getGenericArguments () [0]; // model type: PropertyInfo [] ppInfoArray = modeType. getProperties (); // List of public attributes <PropertyInfo> listPPInfo = ppInfoArray. toList (); // convenient query // key column List <PropertyInfo> keyPIArray = listPPInfo. findAll (x => KeyColumnArray. contains (x. name); List <T> listToDelete = new List <T> (); // DataRow [] drAddArray = source. select ("", "", DataViewRowState. added); object objItem = modeType. assembly. createInstance (modeType. fullName); foreach (DataRow dr in drAddArray) {destinationArray. add (T) objItem); foreach (System. reflection. propertyInfo pi in listPPInfo) {pi. setValue (destinationArray [destinationArray. C Ount-1], dr [pi. name], null) ;}// modify and delete data DataView dvForOP = new DataView (source); dvForOP. rowStateFilter = DataViewRowState. deleted | DataViewRowState. modifiedCurrent; foreach (DataRowView drv in dvForOP) {for (int I = 0; I <destinationArray. count; I ++) {bool blIsTheRow = true; // find the row foreach (System. reflection. propertyInfo pInfo in keyPIArray) {object okey = pInfo. getValue (destinati OnArray [I], null); if (okey = null) continue; if (drv [pInfo. Name]. ToString ()! = Okey. ToString () {blIsTheRow = false; break ;}} if (! BlIsTheRow) // non-row continue; // synchronously assigns a switch (drv. row. rowState) {case DataRowState. modified: {foreach (System. reflection. propertyInfo pi in listPPInfo) {if (keyPIArray. contains (pi) // The primary key column does not update continue; pi. setValue (destinationArray [I], drv [pi. name], null) ;}} break; case DataRowState. deleted: {listToDelete. add (destinationArray [I]);} break ;}}for (int I = 0; I <listToDelete. count; I ++) {destinationArray. remove (listToDelete [I]);} return true ;}

Iii. ConvertModelToDataTable:

Converts an object class set to a able.The params parameter is interesting.You can check it.

/// <Summary> /// convert a generic collection class to a DataTable // </summary> /// <typeparam name = "T"> set item type </typeparam> /// <param name = "sourceArray"> set </param> /// <param name = "propertyNameArray"> name of the column to be returned, to return all columns, enter a null value </param> // <returns> dataset (table) </returns> public static DataTable ConvertModelToDataTable <T> (IList <T> sourceArray, params string [] propertyNameArray) where T: class {List <string> propertyNameList = new Lis T <string> (); if (propertyNameArray! = Null) propertyNameList. addRange (propertyNameArray); DataTable result = new DataTable (); // obtain the structure Type [] typeArr = sourceArray. getType (). getGenericArguments (); if (typeArr. length = 0) return result; PropertyInfo [] propertys = typeArr [0]. getProperties (); foreach (PropertyInfo pi in propertys) {if (propertyNameList. count = 0) {result. columns. add (pi. name, pi. propertyType);} else {if (propertyNameList. contains (pi. name) result. columns. add (pi. name, pi. propertyType) ;}}for (int I = 0; I <sourceArray. count; I ++) {ArrayList tempList = new ArrayList (); foreach (PropertyInfo pi in propertys) {if (propertyNameList. count = 0) {object obj = pi. getValue (sourceArray [I], null); tempList. add (obj);} else {if (propertyNameList. contains (pi. name) {object obj = pi. getValue (sourceArray [I], null); tempList. add (obj) ;}} object [] array = tempList. toArray (); result. loadDataRow (array, true);} return result ;}

Iv. ConvertDataViewToModel:

Convert the content in Dataview into an object.

/// <Summary> /// convert the view to a generic set /// </summary> /// <typeparam name = "T"> type </typeparam>/ // <param name = "dataView"> View </param> // <param name = "model"> generic instance </param> /// <returns> </returns> public static List <T> ConvertDataViewToModel <T> (DataView dataView, T model) where T: class {List <T> listReturn = new List <T> (); Type modelType = model. getType (); DataTable dt = dataView. table; // obtain all types of the model. PropertyInfo [] modelProperties = modelType. getProperties (); // traverse all rows and add the object for (int I = 0; I <dt. rows. count; I ++) {object obj = modelType. assembly. createInstance (modelType. fullName); listReturn. add (T) obj); // traverses all attributes of the model, foreach (PropertyInfo pi in modelProperties) {// traverses all columns, foreach (DataColumn col in dt. columns) {// if the column data type is the same as the model data type, the name is the same if (col. dataType = pi. propertyType & col. columnName = pi. name) {pi. setValue (obj, dt. rows [I] [col. columnName], null) ;}}} return listReturn ;}
UnitTest

This UntTest is relatively simple, and the coverage rate is not 100%. It's almost. Now, we have to take a rest and simply get two testing methods. As follows:

[TestMethod] public void TestConvertDataTableToModel () {DataTable dt = new DataTable (); dt. columns. add ("Id", typeof (string); dt. columns. add ("Name", typeof (string); dt. columns. add ("Address", typeof (string); dt. primaryKey = new DataColumn [] {dt. columns [0]}; dt. rows. add ("0001", "Zhang San", "Wuhan"); dt. rows. add ("0002", "Li Si", "Beijing"); dt. acceptChanges (); dt. rows. add ("0003", "Wang Wu", "Shenzhen City"); List <People> allPeople = new List <People> (); TransformUtil. convertDataTableToModel <People> (dt, allPeople); // Assert whether there is only one data, and Assert is the only one Who modifies the status. areEqual (allPeople. count, 1); Assert. areEqual (allPeople [0]. name, "Wang Wu ");}
[TestMethod] public void TestConvertModelToDataTable () {List <People> allPeople = new List <People> () {new People () {Id = "0001", Name = "Zhang San ", address = "Wuhan"}, new People () {Id = "0002", Name = "Li Si", Address = "Beijing"}, new People () {Id = "0003", Name = "Wang Wu", Address = "Shenzhen City" }}; DataTable dt = TransformUtil. convertModelToDataTable <People> (allPeople, null); // whether there are three rows of data, three columns of data, Id of column 1st, and Assert of Column 2 in the first row. areEqual (dt. rows. count, 3); Assert. areEqual (dt. columns. count, 3); Assert. areEqual (dt. columns [0]. columnName, "Id"); Assert. areEqual (dt. rows [0] [1], "James ");}}

The test results are as follows:

Both test cases pass.

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.