0

我正在处理一些项目(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 个适配器的数据?

4

1 回答 1

1

我使用SqlDataAdapter.RowUpdated事件来“捕捉”最近添加的记录的身份,但似乎有很多不同的可能性: http: //www.mikesdotnetting.com/article/54/getting-the-identity-of-最近添加的记录

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

于 2014-11-27T15:29:58.183 回答