当前位置:网站首页>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
边栏推荐
- HDU4876ZCC loves cards(多校题)
- Codeforces Round #275 (Div. 2) C – Diverse Permutation (构造)[通俗易懂]
- Unity3d 4.3.4f1执行项目
- Solve the problem that the executable file of /bin/sh container is not found
- uva 12230 – Crossing Rivers(概率)「建议收藏」
- Klocwork code static analysis tool
- Differences and connections between MinGW, mingw-w64, tdm-gcc and other tool chains "suggestions collection"
- CodeSonar如何帮助无人机查找软件缺陷?
- Mysql子查询关键字的使用方式(exists)
- Measure the height of the building
猜你喜欢
上海交大最新《标签高效深度分割》研究进展综述,全面阐述无监督、粗监督、不完全监督和噪声监督的深度分割方法
AADL Inspector 故障树安全分析模块
The latest version of codesonar has improved functional security and supports Misra, c++ parsing and visualization
MySQL约束之默认约束default与零填充约束zerofill
解决使用uni-app MediaError MediaError ErrorCode -5
Klocwork code static analysis tool
Tensorflow2. How to run under x 1 Code of X
Mongodb learn from simple to deep
ERROR: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your
Don't fall behind! Simple and easy-to-use low code development to quickly build an intelligent management information system
随机推荐
Can Huatai Securities achieve Commission in case of any accident? Is it safe to open an account
SQL注入报错注入函数图文详解
凌云出海记 | 赛盒&华为云:共助跨境电商行业可持续发展
嵌入式系统真正安全了吗?[ OneSpin如何为开发团队全面解决IC完整性问题 ]
最新版本的CodeSonar改进了功能安全性,支持MISRA,C ++解析和可视化
私募基金在中國合法嗎?安全嗎?
uva 12230 – Crossing Rivers(概率)「建议收藏」
Dachang classic pointer written test questions
Is it safe to open an account online now? I want to know where I can open an account in Nanning now?
Helix QAC 2020.2 new static test tool maximizes the coverage of standard compliance
DataTable数据转换为实体
现在网上开户安全么?想知道我现在在南宁,到哪里开户比较好?
Intelligent transportation is full of vitality. What will happen in the future? [easy to understand]
目前股票开户安全吗?可以直接网上开户吗。
恶魔奶爸 B2 突破语法,完成正统口语练习
awk处理JSON处理
Cantata9.0 | 全 新 功 能
目标:不排斥 yaml 语法。争取快速上手
Écrivez une liste de sauts
如何满足医疗设备对安全性和保密性的双重需求?