使用自定义属性将对象序列化到/从 SQL Server 表






4.25/5 (8投票s)
展示了如何使用自定义属性将 .NET 类直接保存到 SQL Server 表
引言
这个类库是一个快速实现,用于使用自定义属性将 .NET 类序列化到/从 SQL Server 数据库表。它比较简单,因为它假定类和表之间存在一对一的映射关系。
涉及的类
DatabaseTableAttribute
此类继承自 Attribute
,用于标识对象读取/写入的表。
DatabaseFieldAttribute
此类继承自 Attribute
,用于标识属性读取/写入的字段。
SQLTableInterop
此类处理对象和表之间的交互。
SQLUtilities
包含一些 SQL Server 实用函数的类。
使用示例
假设我们有一个名为 [Currency
] 的表,定义如下
CREATE TABLE Currency
(
[Currency Code] char(3), --key
[Currency Name] varchar(200)
)
那么我们可以创建一个 .NET 类,该类可以保存和读取此表,如下所示
<DatabaseTableAttribute("CURRENCY")> _
Public Class Staff
Private _Code As String
Private _Name As String
Public Sub New(Byval Code As String)
_Code = Code
Dim SQLTableInterop As New SQLTableInterop(ConnectionString)
SQLTableInterop.GetObjectDataFromTable(Me)
End Sub
<DatabaseFieldAttribute("Currency Code",True)> _
Public ReadOnly Property CurrencyCode() As String
Get
Return _Code
End Get
End Property
<DatabaseFieldAttribute("Currency Name",False)> _
Public Property CurrencyName() As String
Get
Return _Name
End Get
Set(ByVal Value As String)
If Value <> _Name Then
_Name = Value
End If
End Set
End Property
Public Sub Save()
Dim SQLTableInterop As New SQLTableInterop(ConnectionString)
SQLTableInterop.SetObjectDataToTable(Me)
End Sub
显然,此实用 DLL 对于更大的表来说,实用性会提高。
历史
- 2005 年 11 月 1 日 - 将代码更改为使用参数化查询,而不是将值构建到查询中,以防止 SQL 注入类型漏洞