当前位置:网站首页>Datatable data conversion to entity

Datatable data conversion to entity

2022-07-07 21:04:00 Full stack programmer webmaster

Hello everyone , I meet you again , I'm the king of the whole stack .

When we write software in a three-tier architecture , We often encounter the following problems , It's the problem of parameter transfer between the three layers : Suppose we were D Layer query data yes DataTable Type of , So we're in B Layers even U When the layer uses this data , To use DataTable Type passed back and forth , No matter what , We will inevitably have to fill in the read fields . For example, we need to use a field of the first record . The code needs to be written like this :mrc.count(*)rows(*). There are many disadvantages in writing like this :

1、easy Wrong writing , And the compiler cannot be checked ;

2、 We need to understand the structure of the database in detail ;

3、 It does not conform to the idea of object-oriented programming .

This problem has been studied for a long time , I searched countless materials , Finally found a solution . take DataTable Data is transformed into a single entity class . Then put these entity classes into the generic collection .

The result diagram is as follows :

Entity class is the mapping of database , Each record corresponds to an entity . The attribute of the entity corresponds to the field of each record , And it is corresponding one by one . Here, we extract every piece of data queried as an entity , These entities are then stored in generic collections . In this way, when we use data, we only need to know the attributes , Use codes such as the following :List.(items).property. such . Does it simplify the code , Reduced workload , It also reduces the error rate .

that . How is it implemented in code ? The first is entity class , here , If there are only two fields in the database, user Minhe password:

Public Class User
	Public UserName As String
	Public PassWord As String
	Public Property _username() As String
	        Get
	            Return UserName
	        End Get
	        Set(value As String)
	            UserName = value
	        End Set
	    End Property
	    Public Property _password() As String
	        Get
	            Return PassWord
	        End Get
	        Set(value As String)
	            PassWord = value
	        End Set
	    End Property
End Class

here . I used one ModelHelper Class to implement this function . Because this is a class about parameters , Put this class in Model layer . The code is as follows :

Imports System.Collections.Generic    ' Namespace 
Imports System.Reflection            ' Introduce reflection : Easy to use propertyInfo
''' <summary>
'''  Entity conversion class . This class is used to convert data tables into entity sets 
''' </summary>
''' <remarks></remarks>
Public Class ModeHelper
    Public Function convertToList(Of T As {New})(ByVal dt As DataTable) As IList(Of T)
        ' take dataTable Convert to generic collection 
        '1convertToList(Of T As {New}) there new Is used to constrain parameters T Of . Otherwise, an error will appear when instantiating 
        '2List The following parameters are always (of +) type 
        Dim myList As New List(Of T)   ' Define the set of return values 
        Dim myType As Type = GetType(T)   ' Define entity class type name 
        Dim dr As DataRow           ' Define rowset 

        Dim tempName As String = String.Empty    ' Define a temporary variable , For storage 
        ' The data table is always a two-dimensional table , You need to use an array :dr and pr,dt Express sqlhelper Return results 
        For Each dr In dt.Rows      ' Traverse DataTable All records 
            Dim myT As New T       ' Define an entity object 
            Dim Propertys() As PropertyInfo = myT.GetType().GetProperties()   ' Define attribute set , Get public properties 
            Dim pr As PropertyInfo
            For Each pr In Propertys    ' Traverse DataTable All fields 
                tempName = pr.Name     ' Assign the attribute name to the temporary variable 
                ' Check Datatable Whether to include this column ( Name == Object property name )
                If (dt.Columns.Contains(tempName)) Then   ' Associate this property with datatable Column name comparison of , see datatable Whether to include this column 
                    If (pr.CanWrite = False) Then          ' Infer whether this attribute has Setter
                        Continue For        ' Carry on 
                    End If
                    Dim value As Object = dr(tempName)     ' Define an object-oriented variable to save the value of the column 
                    If (value.ToString <> DBNull.Value.ToString()) Then    ' Suppose it is not empty , Then pay the attribute of the object 
                        pr.SetValue(myT, value, Nothing)          ' During execution , By reflection , Dynamically access the properties of an object 
                    End If
                End If
            Next
            myList.Add(myT)      ' Add to set 
        Next
        Return myList    ' Return results 
    End Function
End Class

Below is D Layer calling code :

Public Function SelectUsers1(user ) As List(Of Charge.Model.User)
	Dim mrc as dataTable         ' If mrc It is queried from the database DataTable Data sheet 
	Dim myList As List(Of Charge.Model.User)     ' Define a set to return the converted entity set 
	Dim mHelper As New Charge.Model.ModeHelper   ' Instantiate an entity transformation class 
	myList = mHelper.convertToList(Of Charge.Model.User)(mrc)    ' Call the method of entity transformation class , Conversion data 
	Return myList    ' Return results 
End Function

ad locum , We will only discuss DataTable Data type conversion problem . Other issues will not be discussed , Everything is based on if , The reference code needs to be careful .

So far , These codes overcome the problems I encountered . But think carefully . Here, an entity corresponds to a record in the database , in other words . Each table will have an entity class or generic collection to correspond , But suppose it is a joint query of multiple tables . How to solve it ? I haven't solved the problem yet , Leave it to be solved later .

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/116450.html Link to the original text :https://javaforall.cn

原网站

版权声明
本文为[Full stack programmer webmaster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071843026329.html