Dim data As New DataSet
Dim parentTable = data.Tables.Add()
Dim childTable = data.Tables.Add()
Dim parentKey As DataColumn
Dim childKey As DataColumn
Dim foreignKey As DataColumn
With parentTable.Columns
parentKey = .Add("ParentId", GetType(Integer))
.Add("ParentName", GetType(String))
End With
With childTable.Columns
childKey = .Add("ChildId", GetType(Integer))
foreignKey = .Add("ParentId", GetType(Integer))
.Add("ChildName", GetType(String))
End With
parentKey.AutoIncrement = True
childKey.AutoIncrement = True
parentTable.PrimaryKey = {parentKey}
childTable.PrimaryKey = {childKey}
Dim relation As New DataRelation("ParentChild", parentKey, foreignKey, True)
relation.ChildKeyConstraint.UpdateRule = Rule.Cascade
'Add a parent row and let a temporary parent ID be generated.
Dim parentRow = parentTable.Rows.Add(DBNull.Value, "First Parent")
'Add a child row and use the temporary parent ID as the foreign key value.
Dim childRow = childTable.Rows.Add(DBNull.Value, parentRow("ParentId"), "FirstChild")
'After insert a parent record, select the last generated ID back into the ParentId column of parentTable.
Dim parentSql = "INSERT INTO Parent (ParentName) VALUES (@ParentName); SELECT ParentId = SCOPE_IDENTITY()"
Dim childSql = "INSERT INTO Child (ParentId, ParentName) VALUES (@ParentId, ChildName)"
Using connection As New SqlConnection("connection string here"),
parentCommand As New SqlCommand(parentSql, connection),
childCommand As New SqlCommand(childSql, connection),
parentAdapter As New SqlDataAdapter With {.InsertCommand = parentCommand},
childAdapter As New SqlDataAdapter With {.InsertCommand = childCommand}
parentCommand.Parameters.Add("@ParentName", SqlDbType.VarChar, 50, "ParentName")
With childCommand.Parameters
.Add("@ParentId", SqlDbType.Int, 0, "ParentId")
.Add("@ChildName", SqlDbType.VarChar, 50, "ChildName")
End With
connection.Open()
'Save the new parent record(s), which will also retrieve the generated ID(s),
'which will be propagated to the child table by the DataRelation.
parentAdapter.Update(parentTable)
'Save the new child record(s), which now contain the correct foreign key value(s).
childAdapter.Update(childTable)
End Using