当前位置:网站首页>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
边栏推荐
- 论文解读(ValidUtil)《Rethinking the Setting of Semi-supervised Learning on Graphs》
- npm uninstall和rm直接删除的区别
- 201215-03-19—cocos2dx内存管理–具体解释「建议收藏」
- Nebula Importer 数据导入实践
- 目标:不排斥 yaml 语法。争取快速上手
- 恶魔奶爸 A0 英文零基础的自我提升路
- 【矩阵乘】【NOI 2012】【cogs963】随机数生成器
- Is embedded system really safe? [how does onespin comprehensively solve the IC integrity problem for the development team]
- gridView自己定义做时间排版「建议收藏」
- Alibaba cloud award winning experience: how to mount NAS file system through ECS
猜你喜欢
C语言 整型 和 浮点型 数据在内存中存储详解(内含原码反码补码,大小端存储等详解)
嵌入式系统真正安全了吗?[ OneSpin如何为开发团队全面解决IC完整性问题 ]
Airiot helps the urban pipe gallery project, and smart IOT guards the lifeline of the city
Measure the height of the building
How does codesonar help UAVs find software defects?
ERROR: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your
Klocwork code static analysis tool
如何满足医疗设备对安全性和保密性的双重需求?
Tensorflow2. How to run under x 1 Code of X
Static analysis of software defects codesonar 5.2 release
随机推荐
刚开户的能买什么股票呢?炒股账户安全吗
MySQL storage expression error
FatMouse&#39; Trade (Hangdian 1009)
Airiot helps the urban pipe gallery project, and smart IOT guards the lifeline of the city
Word inversion implements "suggestions collection"
写一下跳表
Lingyun going to sea | yidiantianxia & Huawei cloud: promoting the globalization of Chinese e-commerce enterprise brands
I have to use my ID card to open an account. Is the bank card safe? I don't understand it
恶魔奶爸 A0 英文零基础的自我提升路
Flask1.1.4 werkzeug1.0.1 source code analysis: Routing
Numerical method for solving optimal control problem (0) -- Definition
Mahout-Pearson correlation的实现
Implement secondary index with Gaussian redis
Details of C language integer and floating-point data storage in memory (including details of original code, inverse code, complement, size end storage, etc.)
Update iteration summary of target detection based on deep learning (continuous update ing)
Codeforces round 296 (Div. 2) A. playing with paper[easy to understand]
使用高斯Redis实现二级索引
如何满足医疗设备对安全性和保密性的双重需求?
软件缺陷静态分析 CodeSonar 5.2 新版发布
[concept of network principle]