当前位置:网站首页>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
边栏推荐
- OneSpin 360 DV新版发布,刷新FPGA形式化验证功能体验
- Codeforces 474 F. Ant colony
- Le capital - investissement est - il légal en Chine? C'est sûr?
- 最新版本的CodeSonar改进了功能安全性,支持MISRA,C ++解析和可视化
- Write a jump table
- Is private equity legal in China? Is it safe?
- 刚开户的能买什么股票呢?炒股账户安全吗
- Optimization cases of complex factor calculation: deep imbalance, buying and selling pressure index, volatility calculation
- HOJ 2245 浮游三角胞(数学啊 )
- Update iteration summary of target detection based on deep learning (continuous update ing)
猜你喜欢
Small guide for rapid formation of manipulator (11): standard nomenclature of coordinate system
Measure the height of the building
AADL inspector fault tree safety analysis module
Nebula Importer 数据导入实践
C语言 整型 和 浮点型 数据在内存中存储详解(内含原码反码补码,大小端存储等详解)
Helix QAC 2020.2新版静态测试工具,最大限度扩展了标准合规性的覆盖范围
Make this crmeb single merchant wechat mall system popular, so easy to use!
使用枚举实现英文转盲文
Static analysis of software defects codesonar 5.2 release
C语言多角度帮助你深入理解指针(1. 字符指针2. 数组指针和 指针数组 、数组传参和指针传参3. 函数指针4. 函数指针数组5. 指向函数指针数组的指针6. 回调函数)
随机推荐
Codeforces 474 F. Ant colony
Update iteration summary of target detection based on deep learning (continuous update ing)
凌云出海记 | 易点天下&华为云:推动中国电商企业品牌全球化
ERROR: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your
C语言 整型 和 浮点型 数据在内存中存储详解(内含原码反码补码,大小端存储等详解)
阿洛的烦恼
OneSpin 360 DV新版发布,刷新FPGA形式化验证功能体验
目标:不排斥 yaml 语法。争取快速上手
Data sorting in string
2022年在启牛开中银股票的账户安全吗?
Small guide for rapid formation of manipulator (11): standard nomenclature of coordinate system
Écrivez une liste de sauts
Tensorflow2.x下如何运行1.x的代码
You want to kill a port process, but you can't find it in the service list. You can find this process and kill it through the command line to reduce restarting the computer and find the root cause of
The latest version of codesonar has improved functional security and supports Misra, c++ parsing and visualization
Codeforces round 296 (Div. 2) A. playing with paper[easy to understand]
MySQL约束之默认约束default与零填充约束zerofill
Lex & yacc of Pisa proxy SQL parsing
软件缺陷静态分析 CodeSonar 5.2 新版发布
Onespin | solve the problems of hardware Trojan horse and security trust in IC Design