按顺序保存2个SqlDataAdapters的数据

时间:2014-11-26 20:15:45

标签: sql-server vb.net save bindingsource bindingnavigator

我正在开发一些项目(VB.Net& SQL Server) 病人和预约方案。

这些是公开声明:

    Dim DS As New DataSet
    Dim SqlAdap, SqlAdapAppointment As SqlDataAdapter
    Dim BindSrc, BindSrcAppointment As New BindingSource

我在Load事件中设置了绑定:

    SqlAdap = New SqlDataAdapter(String.Format("select * from {0}",Patient),SqlConMain)
    SqlAdap.Fill(DS,"Patient")
    Dim SqlCmd As New SqlCommandBuilder(SqlAdap)
    SqlAdap.InsertCommand = SqlCmd.GetInsertCommand
    SqlAdap.DeleteCommand = SqlCmd.GetDeleteCommand
    SqlAdap.UpdateCommand = SqlCmd.GetUpdateCommand
    BindSrc.DataSource = DS
    BindSrc.DataMember = "Patient"
    BindNavMain.BindingSource = BindSrc

    SqlAdapAppointment = New SqlDataAdapter("select * from Appointment", SqlConMain)
    SqlAdapAppointment.Fill(DS, "Appointment")
    Dim SqlCmdAppointment As New SqlCommandBuilder(SqlAdapAppointment)
    SqlAdapAppointment.InsertCommand = SqlCmdAppointment.GetInsertCommand
    SqlAdapAppointment.DeleteCommand = SqlCmdAppointment.GetDeleteCommand
    SqlAdapAppointment.UpdateCommand = SqlCmdAppointment.GetUpdateCommand

    Dim Rel As New DataRelation("FK_Patient_Appointment",
     DS.Tables("Patient").Columns("PatientId"),
     DS.Tables("Appointment").Columns("PatientId"), False)

    Rel.Nested = False
    DS.Relations.Add(Rel)
    BindSrcAppointment.DataSource = BindSrc
    BindSrcAppointment.DataMember = "FK_Patient_Appointment"
    BindNavAppointment.BindingSource = BindSrcAppointment
一切顺利.. 但如果我使用BindingNavigator添加新患者,则使用约会的BindingNavigator为他添加预约

然后我尝试保存所有这些,它会成功保存患者数据,但之后会抛出错误,因为它无法保存与新患者ID相关的预约数据

这是我的保存代码:

    BindSrcAppointment.EndEdit()
    BindSrc.EndEdit()

    Dim TblPatient As DataTable = DS.Tables("Patient").GetChanges()

    If TblPatient IsNot Nothing Then
        SqlAdap.Update(TblPatient)
        DS.Tables("Patient").AcceptChanges()
    End If

    Dim TblAppointment As DataTable = DS.Tables("Appointment").GetChanges()

    If TblAppointment IsNot Nothing Then
        SqlAdapAppointment.Update(TblAppointment)
        DS.Tables("Appointment").AcceptChanges()
    End If

如果我尝试将已预约数据已保存到数据库的患者添加约会,那么当然会成功保存

但我想知道是否有办法一次性保存2个适配器的数据?

1 个答案:

答案 0 :(得分:1)

我使用SqlDataAdapter.RowUpdated事件来抓住'最近添加的记录的标识,但似乎有很多不同的可能性: http://www.mikesdotnetting.com/article/54/getting-the-identity-of-the-most-recently-added-record

因此,您必须更新Patient表,检索最近添加的记录的自动增量标识值,然后更新Appointment表。