2007年7月4日星期三

关于VB2005中自动生成TableAdapter的事务处理

最近用vb2005做程序,在用事务处理多个TableAdapter时遇到了困难,TableAdapter是DataAdapter的包装后类型,无法直接提取InsertCommand、DeleteCommand、UpdateCommand属性,无法使用SqlTransaction进行处理,上网找了找,有一篇 关于VS2005中自动生成TableAdapter的事务处理 ,恍然大悟,原来可以这样做,遂照葫芦画瓢。

Namespace DataAccess.DataSet1TableAdapters
Partial Class Table1TableAdapter
ReadOnly Property MyAdapter() As SqlDataAdapter
Get
Return Me._adapter
End Get
End Property
End Class

Partial Class Table2TableAdapter
ReadOnly Property MyAdapter() As SqlDataAdapter
Get
Return Me._adapter
End Get
End Property
End Class
End Namespace

Dim Conn As New SqlClient.SqlConnection(ConnString)
Table1TableAdapter.Connection = Conn
Table1TableAdapter.Connection = Conn
Dim SqlTran As SqlTransaction

Try
Conn.Open()
SqlTran = Conn.BeginTransaction

Table1TableAdapter.MyAdapter.InsertCommand.Transaction = SqlTran
Table1TableAdapter.MyAdapter.DeleteCommand.Transaction = SqlTran
Table1TableAdapter.MyAdapter.UpdateCommand.Transaction = SqlTran
Table2TableAdapter.MyAdapter.InsertCommand.Transaction = SqlTran
Table2TableAdapter.MyAdapter.DeleteCommand.Transaction = SqlTran
Table2TableAdapter.MyAdapter.UpdateCommand.Transaction = SqlTran

Table1TableAdapter.Update(Table1)
Table2TableAdapter.Update(Table2)

SqlTran.Commit()

Catch ex As Exception
SqlTran.Rollback()
Finally
Conn.Close()
End Try

没有评论: