DataTable fill object class return generic set

Source: Internet
Author: User

I found a piece of code from Kun Ge yesterday, as shown below:


To explain this code, after the end of the layer D query, assign the result of the datatable query to the attributes of the object and then return the object process. kun asked me after reading the code, if an object has more than 500 attributes, do you want to write the object one by one? What if multiple objects are returned? At this time, I realized that my code was very problematic. The original design was that each method would return at most one entity, but when multiple records were found, it is really a problem to return to the able even if the layer-3 structure is broken.


How to change it, I suddenly came up with the old method: array + loop, read the column value with loop reading, and save it to the object array. I checked and found that I was too OUT. Obviously there are new and good technologies, but I can't think of them once I used them.


Baidu uses the following method: Add a tool class at the Entity layer, similar to the tool class at the D layer, except that the tool class converts datatable to a generic set containing entities, then, the set is returned as the result every time it is returned.


The best thing about this method is to assign values to each object attribute. The internal attribute set is used to repeatedly assign values, so there is no need to write them one by one. In this way, the encapsulation is better, and make the code more error-prone.


However, the only pity is that using this tool class imposes a condition on the object and the datatable, that is, the attribute name of the object must correspond to the column name of the datatable.


I found a lot of such classes on Baidu, but only found C #, and then I changed a VB. NET version. Below is your DEMO:


First, the object class:

This entity class is a ing of the instructor information table.

Public Class EntityUser Private FilUserName As String 'user name Private FilPwd As string' password Private FilTeaName As string' instructor name Private FilTeaLevel As string' instructor level Private FilRegDate As string' registration date Private FilRegTime As String 'registration time Private FilDelDate As string' logout date Private FilDelTime As string' logout time Private FilOnLineStatue As string' online state ''''''Username ''''''
 '''
 '''
 Public Property UserName () As String Get Return FilUserName End Get Set (ByVal value As String) FilUserName = value End Set End Property ''''''Password ''''''
 '''
 '''
 Public Property Pwd () As String Get Return FilPwd End Get Set (ByVal value As String) FilPwd = value End Set End Property ''''''Instructor name ''''''
 '''
 '''
 Public Property TeaName () As String Get Return FilTeaName End Get Set (ByVal value As String) FilTeaName = value End Set End Property ''''''Instructor level ''''''
 '''
 '''
 Public Property TeaLevel () As String Get Return FilTeaLevel End Get Set (ByVal value As String) FilTeaLevel = value End Set End Property ''''''Registration date ''''''
 '''
 '''
 Public Property RegDate () As String Get Return FilRegDate End Get Set (ByVal value As String) FilRegDate = value End Set End Property ''''''Registration time ''''''
 '''
 '''
 Public Property RegTime () As String Get Return FilDelDate End Get Set (ByVal value As String) FilDelTime = value End Set End Property ''''''Logout date ''''''
 '''
 '''
 Public Property DelDate () As String Get Return FilDelDate End Get Set (ByVal value As String) FilDelDate = value End Set End Property ''''''Logout time ''''''
 '''
 '''
 Public Property DelTime () As String Get Return FilDelTime End Get Set (ByVal value As String) FilDelTime = value End Set End Property ''''''Online statement ''''''
 '''
 '''
 Public Property OnLineStatue () As String Get Return FilOnLineStatue End Get Set (ByVal value As String) FilOnLineStatue = value End Set End PropertyEnd Class


My instructor information table is as follows: there are 3 Records in it. This result will be used for a while.




Then, a SqlHelper is written, and this code is no longer written. This is a DEMO, so the three-layer architecture is not used. When you do this, be sure not to break the overall structure.


The following is the EntityHelper discussed in this article. I don't know if the name is accurate. But if I want to add this class to the layer-3, I will treat it like SQLHelper, add it as a Tool class of the entity layer. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + ICAgICA8YnI + cda-vcd4kphbyzsbjbgfzcz0 = "brush: java;"> Imports System. collections. generic 'adds the Generic namespace Imports System. reflection 'introduce Reflection: to use PropertyInfoPublic Class EntityHelper Public Shared Function convertToList (Of T As {New}) (ByVal dt As DataTable) As IList (Of T) 'convert a able to a generic collect' Note: 1. convertToList (Of T As {New}) The new here is used to constrain T and must exist, otherwise, the error '2 will appear in the new T. The new constraint is in C # and VB. NET is written differently. C # uses where to add constraints to T Dim myList As New List (Of T) 'define the final returned collection Dim myTpye As Type = GetType (T) 'to get the Type name of the object class Dim dr As DataRow' define the row set Dim tempName As String = String. empty 'defines a temporary variable 'to traverse all data rows In the DataTable For Each dr In dt. rows Dim myT As New t' defines the object Dim propertys () As PropertyInfo = myT of an object class. getType (). getProperties () 'define the property set Dim Pr As propertyinfo' to traverse all properties of this object For Each Pr In propertys tempName = Pr. name' assign the attribute Name to the Temporary Variable 'and check whether the DataTable contains this column (column Name = Object attribute Name) If (dt. columns. contains (tempName) Then 'compares this attribute with the list in the datatable to check whether the datatable Contains this attribute' to determine whether the property has a Setter If (Pr. canWrite = False) then' determines whether this attribute can be written. If it cannot be written, the loop "Continue For End If Dim value As Object = dr (tempName)" appears) 'define an object-type variable to save the column value If (value. toString <> DBNull. value. toString () then' if it is not null, the property Pr is assigned to the object. setValue (myT, value, Nothing) 'dynamically accesses the attribute End If Next myList of an object through reflection during runtime. add (myT) 'add to the set Next Return mylist' returns the object set End FunctionEnd Class


At this point, the main classes have been written. The following describes how to call the client:


Dim strSQL As String = "select * from T_TeaInfo where TeaLevel = 'admin'" 'note, this method does not advocate Dim mysqlhelper As New SQLHelper 'to define the query Assistant class Dim dt As New able' to define the queried table set Dim myList As List (Of EntityUser) 'Save the converted generic set dt = mysqlhelper. execSelect (strSQL, CommandType. text) 'execute query' converts dt to the generic set myList = EntityHelper. convertToList (Of EntityUser) (dt) TextBox1.Text = myList. count' the number of instructors displayed in the text box


After running, you can see that the results are as follows:




Summary:

In Layer 3, we may use a Datatable when uploading data from layer D to the upper layer. This is a very broken structure method, I really realized the benefits of the entity before I could use it.

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.