所以我有一个带有父表的 MS Access 数据库:
ID Autonumber
Description Text
子表:
ID AutoNumber
Description Text
ParentID Number
我创建了关系:
Parent column: ID
Child column: ParentID
Enforce Ref Integrity, Cascade Update and Cascade Delete
我已将其放入 Visual Studio 2010 中,向导已创建数据集和适配器。我已修改 xsd 以将关系设置为 ,Both Relation and Foreign Key Constraint
并将Update/Delete
规则设置为Cascade
.
所以我尝试添加一个带有关联子记录的父记录:
var taParent = new TestDataSetTableAdapters.ParentTableAdapter();
var taChild = new TestDataSetTableAdapters.ChildTableAdapter();
var ds = new TestDataSet();
taParent.Fill(ds.Parent);
taChild.Fill(ds.Child);
var rowParent = ds.Parent.NewParentRow();
rowParent.Description = DateTime.Now.ToString();
ds.Parent.AddParentRow(rowParent);
var rowChild = ds.Child.NewChildRow();
rowChild.ChildText = DateTime.Now.ToString();
ds.Child.AddChildRow(rowChild);
taParent.Update(ds);
var parentId = rowParent.ID; // <-- This is still -1
// taParent.Fill(ds.Parent); // <-- Doing this hoping to reload the parent record gives: Cannot clear table Parent because ForeignKeyConstraint ParentChild enforces constraints and there are child rows in Child.
taChild.Update(ds.Child);
但子记录 ParentID 为空。
如果我尝试:
rowChild.SetParentRow(rowParent);
我去拿
You cannot add or change a record because a related record is required in table 'Parent'.
我错过了什么?