Hi
Defining a foreign key constraint will ensure that no child rows can add without a parent key. Can use the cascade type for update and delete rule and enforce constraints to true for safe delete and update.
For example..
private void Form1_Load(object sender, EventArgs e)
{
DataSet dataSet2 = new DataSet("TestDataset");
DataTable t1 = new DataTable("Parent");
DataColumn t1col1 = new DataColumn("ParentId", typeof(int));
t1col1.AllowDBNull = false;
t1col1.AutoIncrement = true;
t1col1.AutoIncrementSeed = 1;
t1col1.AutoIncrementStep = 1;
t1col1.Unique = true;
DataColumn t1col2 = new DataColumn("Name", typeof(string));
t1.Columns.Add(t1col1);
t1.Columns.Add(t1col2);
DataTable t2 = new DataTable("Child");
DataColumn t2col1 = new DataColumn("ChildId", typeof(int));
t2col1.AllowDBNull = false;
t2col1.AutoIncrement = true;
t2col1.AutoIncrementSeed = 1;
t2col1.AutoIncrementStep = 1;
t2col1.Unique = true;
DataColumn t2col2 = new DataColumn("Name", typeof(string));
DataColumn t2col3 = new DataColumn("ParentId", typeof(int));
t2col3.AllowDBNull = false;
t2.Columns.Add(t2col1);
t2.Columns.Add(t2col2);
t2.Columns.Add(t2col3);
dataSet2.Tables.Add(t1);
dataSet2.Tables.Add(t2);
DataRelation rel = new DataRelation("Rel1", t1col1, t2col1);
dataSet2.Relations.Add(rel);
Constraint parent_child_link = new ForeignKeyConstraint("ParentChildRel", t1col1,t2col3);
t2.Constraints.Add(parent_child_link);
DataRow pRow = dataSet2.Tables["Parent"].NewRow();
pRow["Name"] = "Parent1";
dataSet2.Tables["Parent"].Rows.Add(pRow);
DataRow cRow = dataSet2.Tables["Child"].NewRow();
cRow["Name"] = "Child1";
cRow["ParentId"] = 1;
dataSet2.Tables["Child"].Rows.Add(cRow);
}
This works fine, but if you remove this code block....
DataRow pRow = dataSet2.Tables["Parent"].NewRow();
pRow["Name"] = "Parent1";
dataSet2.Tables["Parent"].Rows.Add(pRow);
It won't work as there is a foreign key violation..So you are safe you won't violate the constraint and handle this error as you wish , to notify error or handle it in a intelligent way