当前位置:网站首页>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 Classhere . 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 ClassBelow 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 Functionad 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
边栏推荐
- Klocwork code static analysis tool
- 程序猿赚的那点钱算个P啊!
- 恶魔奶爸 A1 语音听力初挑战
- 目标:不排斥 yaml 语法。争取快速上手
- 单词反转实现「建议收藏」
- What are the official stock trading apps in the country? Is it safe to use
- CodeSonar如何帮助无人机查找软件缺陷?
- 软件缺陷静态分析 CodeSonar 5.2 新版发布
- C语言多角度帮助你深入理解指针(1. 字符指针2. 数组指针和 指针数组 、数组传参和指针传参3. 函数指针4. 函数指针数组5. 指向函数指针数组的指针6. 回调函数)
- Lingyun going to sea | saihe & Huawei cloud: jointly help the sustainable development of cross-border e-commerce industry
猜你喜欢

Implement secondary index with Gaussian redis

Airiot helps the urban pipe gallery project, and smart IOT guards the lifeline of the city

Nebula Importer 数据导入实践

最新版本的CodeSonar改进了功能安全性,支持MISRA,C ++解析和可视化
![Is embedded system really safe? [how does onespin comprehensively solve the IC integrity problem for the development team]](/img/af/61b384b1b6ba46aa1a6011f8a30085.png)
Is embedded system really safe? [how does onespin comprehensively solve the IC integrity problem for the development team]

Helix QAC 2020.2新版静态测试工具,最大限度扩展了标准合规性的覆盖范围

ISO 26262 - 基于需求测试以外的考虑因素
Codesonar enhances software reliability through innovative static analysis

I Basic concepts

Intelligent software analysis platform embold
随机推荐
openGl超级宝典学习笔记 (1)第一个三角形「建议收藏」
[concept of network principle]
阿里云有奖体验:如何通过ECS挂载NAS文件系统
Is private equity legal in China? Is it safe?
目标:不排斥 yaml 语法。争取快速上手
C language helps you understand pointers from multiple perspectives (1. Character pointers 2. Array pointers and pointer arrays, array parameter passing and pointer parameter passing 3. Function point
死锁的产生条件和预防处理[通俗易懂]
想杀死某个端口进程,但在服务列表中却找不到,可以之间通过命令行找到这个进程并杀死该进程,减少重启电脑和找到问题根源。
Write a jump table
ERROR: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your
上海交大最新《标签高效深度分割》研究进展综述,全面阐述无监督、粗监督、不完全监督和噪声监督的深度分割方法
Codeforces round 296 (Div. 2) A. playing with paper[easy to understand]
Is it safe to open an account online now? I want to know where I can open an account in Nanning now?
Le capital - investissement est - il légal en Chine? C'est sûr?
阿洛的烦恼
Object-C programming tips timer "suggestions collection"
Do you have to make money in the account to open an account? Is the fund safe?
POJ 3140 Contestants Division「建议收藏」
Mahout-Pearson correlation的实现
恶魔奶爸 B2 突破语法,完成正统口语练习