ADO.NET中关于主键为自动编号的主从表(主祥表)的修改
主从表的结构关系统如下:
主表PT:
pt.字段A——自动编号(主键)
pt.字段B——字符
pt.字段C——字符
从表CT:
ct.字段A——自动编号(主键)
ct.字段B——数字(pt.字段A的值)
ct.字段C——字符
保存代码:
===================================================
Me.Validate()
Try
If Me.DBDataSet.主表PT.GetChanges IsNot Nothing Then
'获取主表PT新增加行的数量
Dim foundRows As DataRow() = Me.DBDataSet.主表PT.Select("", "字段A DESC", DataViewRowState.Added)
If foundRows.Length > 0 Then
Dim command As OleDb.OleDbCommand = Me.主表PTTableAdapter.Connection.CreateCommand()
command.CommandText = "SELECT TOP " & foundRows.Length.ToString & " 字段A FROM 主表PT ORDER BY 字段A DESC"
If Me.主表PTTableAdapter.Connection.State = ConnectionState.Closed Then Me.主表PTTableAdapter.Connection.Open()
'保存主表PT
Me.主表PTTableAdapter.Update(Me.DBDataSet.主表PT)
'获取主表PT新增加的行的真正编号,并修改子关系表
Dim reader As OleDb.OleDbDataReader = command.ExecuteReader()
Dim ParentRowIndex As Integer = 0
While reader.Read()
Dim childRows() As DataRow
Dim relation As DataRelation
Dim childRowIndex As Integer
'
'修改主表PT,使其显示真正的编号
foundRows(ParentRowIndex).Item("字段A") = reader.GetInt32(0)
'修改 从表CT字段B 与 主表PT字段A 相对应的值
For Each relation In Me.DBDataSet.主表PT.ChildRelations
childRows = foundRows(ParentRowIndex).GetChildRows(relation)
For childRowIndex = 0 To childRows.Length - 1
childRows(childRowIndex).Item("字段B") = reader.GetInt32(0)
Next childRowIndex
Next relation
ParentRowIndex = ParentRowIndex + 1
End While
reader.Close()
Me.主表PTTableAdapter.Connection.Close()
Me.DBDataSet.主表PT.AcceptChanges()
Else
'保存主表PT
Me.主表PTTableAdapter.Update(Me.DBDataSet.主表PT)
End If
End If
'保存 从表CT
Me.从表CTTableAdapter.Update(Me.DBDataSet.从表CT)
Me.DBDataSet.从表CT.AcceptChanges()
MessageBox.Show("保存成功!")
Catch ex As Exception
MessageBox.Show("失败原因:" & ex.Message, "保存失败!", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try