且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过关系插入父表和子表

更新时间:2023-02-05 10:34:20

将数据插入到数据表中时,未设置PrimaryKey值.在子表中需要此值作为对父表的引用.因此,首先将数据添加到父表.找到最新的PK值,并在子表的插入内容中使用该值.
When you INSERT data into a datatable the PrimaryKey Value is not set. This value is needed in the child table as a reference to the parent table. So first add data to parent table. Find the newest PK value and use that value in your insert in your child table.


下面是我的代码.
我的测试非常基础.
用户按下新建"按钮,然后尝试创建父记录和子记录.
我在表格上输入数据.
我单击保存"按钮,然后尝试保存数据.

我认识到需要获取新的KeyID来保存到子级的问题,但是问题是当我尝试取回添加的子级行时,什么也没有...

我相信单击新建"按钮时一定会丢失某些东西...当我将记录添加到ChildBindingSource时,它可能没有链接到父记录吗?有没有编程方式来"AddChildRecord"?


私人无效New_Click(对象发送者,EventArgs e)
{
ParentBindingSource.AddNew();
ChildBindingSource.AddNew();
}

私人void SaveBTN_click(object sender,EventArgs e)
{
ParentBindingSource.EndEdit();
ChildBindingSource.EndEdit();
foreach(dataSet11.ParentTable中的DataSet1.ParentRow cr)
{
如果(cr.RowState == DataRowState.Added)
{

/*
调用GetChildRows不会返回任何值!!! ???
*/
DataRow [] childRows = cr.GetChildRows(dataSet11.Relations ["Parent_ChildRelation"]);
ParentTableAdapter.Update(cr);
ChildTableRow childRow =(ChildTableRow)childRows [0];
childRow.KeyID = cr.KeyID;
ChildTableAdapter.Update(childRow);

}
}
Below is my code.
My test is very basic.
The user presses the "New" button and I try to create both a Parent and Child record.
I enter the data on the Form.
I click the "Save" button and try to save the data.

I recognize the need to get the new KeyID to save to the child, but the problem is that when I try to get the child row back that I added, nothing is there...

I believe I must be missing something when I click the New button... When I add the record to the ChildBindingSource perhaps it doesn''t get linked to the parent record? Is there a programmatic way to "AddChildRecord"?


private void New_Click(object sender, EventArgs e)
{
ParentBindingSource.AddNew();
ChildBindingSource.AddNew();
}

private void SaveBTN_click( object sender, EventArgs e)
{
ParentBindingSource.EndEdit();
ChildBindingSource.EndEdit();
foreach (DataSet1.ParentRow cr in dataSet11.ParentTable)
{
if (cr.RowState == DataRowState.Added)
{

/*
The call to GetChildRows doesn''t return any values!!! ???
*/
DataRow[] childRows = cr.GetChildRows(dataSet11.Relations["Parent_ChildRelation"]);
ParentTableAdapter.Update(cr);
ChildTableRow childRow = (ChildTableRow)childRows[0];
childRow.KeyID = cr.KeyID;
ChildTableAdapter.Update(childRow);

}
}