原来的系统是基于DataSet进行离线数据操作的,考虑到扩展性,希望在服务接口上使用对象。鉴于迁移容易,对实体类的实例化稍微研究了一下,做了下面这个实体列表与DataSet之间转换的方法类。希望经验者给予性能方面的意见和建议,如果有好的方法也请告知。我们也考虑过使用Entity Framework,但鉴于无法控制SQL文内容就放弃了,如果各位有好的实践方法请告知。
实体列表与DataSet之间的转换方法类:
Public NotInheritable Class EntityUtility
''转换DataSet到实体列表方法
Public Shared Function ConvertDataSetToEntities(Of T)
(ByVal ds As DataSet) As List(Of T)
''设置DataSet根节点节点名(ArrayOf+实体类名)
ds.DataSetName = "ArrayOf" & GetType(T).Name
''设置DataTable节点名(实体类名)
ds.Tables(0).TableName = GetType(T).Name
''打开DataSet的XML内容字符串读取流
Dim sr As New System.IO.StringReader(ds.GetXml)
''创建XML序列化类
Dim f As New System.Xml.Serialization.XmlSerializer(GetType(List(Of T)))
''将XML反序列化为对象列表
Dim objects As List(Of T) = f.Deserialize(sr)
''关闭XML字符串读取流
sr.Close()
''返回对象列表
Return objects
End Function
''转换实体列表到DataSet
Public Shared Function ConvertEntitesToDataSet(Of T)
(ByVal objects As List(Of T)) As DataSet
''创建XML序列化类
Dim f As New System.Xml.Serialization.XmlSerializer(GetType(List(Of T)))
''创建XML字符串构造器
Dim sb As New System.Text.StringBuilder
''创建XML写入流
Dim sw As New System.IO.StringWriter(sb)
''序列化实体列表到XML写入流
f.Serialize(sw, objects)
''关闭字符串写入流
sw.Close()
''创建DataSet对象
Dim ds As New DataSet
''创建XML对象
Dim sr As New System.IO.StringReader(sb.ToString)
''通过XML读取内容到DataSet
ds.ReadXml(sr)
''关闭XML读取流
sr.Close()
''返回DataSet
Return ds
End Function
End Class
测试代码:
Imports System.Xml.Serialization
Module Module1
Sub Main()
Try
''测试从DataSet转换为实体列表
Dim es As New List(Of Entity)
Dim ds As New DataSet
Dim dt As New DataTable
dt.Columns.Add("COL1")
dt.Columns.Add("COL2")
dt.Columns.Add("COL3")
For i As Integer = 0 To 49
dt.Rows.Add(New String() {"Data" & i.ToString,
"Data" & i.ToString, "Data" & i.ToString})
Next
ds.Tables.Add(dt)
ds.AcceptChanges()
es = EntityUtility.ConvertDataSetToEntities(Of Entity)(ds)
Console.WriteLine("对象列表长度:" & es.Count)
Console.WriteLine("第20个对象的COL2属性值" & es(20).COL2)
''从对象列表转换到DataSet
Dim ds2 As DataSet = EntityUtility.
ConvertEntitesToDataSet(Of Entity)(es)
Console.WriteLine(ds2.GetXml)
Catch ex As Exception
Console.WriteLine(ex.ToString)
Finally
Console.ReadKey()
End Try
End Sub
End Module
''数据实体定义
<Serializable()> _
<XmlRootAttribute("Entity", IsNullable:=False)> _
Public Class Entity
Private mCOL1 As String
Public Property COL1() As String
Get
Return mCOL1
End Get
Set(ByVal value As String)
mCOL1 = value
End Set
End Property
Private mCOL2 As String
Public Property COL2() As String
Get
Return mCOL2
End Get
Set(ByVal value As String)
mCOL2 = value
End Set
End Property
Private mCOL3 As String
Public Property COL3() As String
Get
Return mCOL3
End Get
Set(ByVal value As String)
mCOL3 = value
End Set
End Property
End Class
刚开始从DataSet的概念转换到O/R Mapping的概念,可能有些落俗套,希望大家批评指正。
标签:
本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@pclwef.cn
文章转载自:博客园