Hi Chris,
I still can't reproduce the problem. I followed your specifications and
wrote the following code, which results in no errors, 3 records persisted in
the parent database table and all related child records having a RowState of
Added:
// Note: I tried with an auto-increment PK and with a string PK
// and both produced the same results
DataSet data = new DataSet();
DataTable parent = data.Tables.Add("ParentTable");
DataColumn pk = parent.Columns.Add("ParentID", typeof(int));
pk.AutoIncrement = true;
pk.AllowDBNull = false;
pk.ReadOnly = true;
parent.Constraints.Add("PK_ParentID", pk, true);
parent.Columns.Add("Text", typeof(string));
DataTable child = data.Tables.Add("ChildTable");
child.Columns.Add("ChildID", typeof(string));
child.Columns.Add("ParentID", typeof(int));
ForeignKeyConstraint foreignKeyConstraint =
(ForeignKeyConstraint) child.Constraints.Add("FK_Child_Parent",
parent.Columns[0], child.Columns[1]);
foreignKeyConstraint.UpdateRule = Rule.Cascade;
child.Rows.Add("C1",
parent.Rows.Add(null, "P1")["ParentID"]);
child.Rows.Add("C2",
parent.Rows.Add(null, "P2")["ParentID"]);
child.Rows.Add("C3",
parent.Rows.Add(null, "P3")["ParentID"]);
foreach (DataRow row in parent.Rows)
Debug.Assert(row.RowState == DataRowState.Added);
foreach (DataRow row in child.Rows)
Debug.Assert(row.RowState == DataRowState.Added);
using (SqlConnection connection = new SqlConnection(
Properties.Settings.Default.TestingConnectionString))
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
using (SqlCommand command = new SqlCommand(
@"INSERT ParentTable SELECT @Text;
SELECT SCOPE_IDENTITY();", connection))
{
command.Parameters.Add("@Text", SqlDbType.NVarChar, 50, "Text");
adapter.AcceptChangesDuringUpdate = false;
adapter.InsertCommand = command;
adapter.Update(parent); // parent is a DataTable
}
}
}
foreach (DataRow row in parent.Rows)
// check for Modified since pk is updated by adapter
Debug.Assert(row.RowState == DataRowState.Modified,
row["Text"].ToString() + ": Invalid parent RowState: " +
row.RowState.ToString());
foreach (DataRow row in child.Rows)
Debug.Assert(row.RowState == DataRowState.Added,
row["ChildID"].ToString() + ": Invalid child RowState: " +
row.RowState.ToString());
MessageBox.Show("Done!");