我一直在努力让我的 SqlDataAdapters 一起工作以通过单个 SQL 事务将一行插入到父表和子表中。我似乎无法从父级获取 ID 级联到子表。
我正在使用 MSSQL 2012。我在 dbo.parent ID 和 dbo.child parent_id 列之间设置了外键约束。下面代码的结果是:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Child_Parent". The conflict occurred in database "Test_Project", table "dbo.Parent", column'id'.
The statement has been terminated.
我希望有人可以帮助我填补缺失的空白,以使代码正常工作。非常感谢!:)
SqlConnection sqlConn = new SqlConnection("Data Source=(Local);Initial Catalog=Test_Project;Integrated Security=True;");
DataSet ds = new DataSet();
// Fetch Data from both tables
SqlDataAdapter parentAdapter = new SqlDataAdapter("SELECT * FROM Parent", sqlConn);
parentAdapter.FillSchema(ds, SchemaType.Source, "Parent");
parentAdapter.Fill(ds, "Parent");
SqlDataAdapter childAdapter = new SqlDataAdapter("SELECT * FROM Child", sqlConn);
childAdapter.FillSchema(ds, SchemaType.Source, "Child");
childAdapter.Fill(ds, "Child");
// Not sure if this step is necessary but I included it for good measure.
ds.Relations.Add(new DataRelation("ParentChildRelation", ds.Tables["Parent"].Columns["id"], ds.Tables["Child"].Columns["parent_id"], true));
// Now add some data...
DataRow parentDr = ds.Tables["Parent"].NewRow();
parentDr["name"] = "Parent1";
ds.Tables["Parent"].Rows.Add(parentDr);
DataRow childDr = ds.Tables["Child"].NewRow();
childDr["parent_id"] = parentDr["id"]; // <- This column always fills NULL.
childDr["name"] = "Child1";
childDr.SetParentRow(parentDr, ds.Relations["ParentChildRelation"]);
ds.Tables["Child"].Rows.Add(childDr);
// Call DataSet updates back to SQL
SqlCommandBuilder parentCmdBuilder = new SqlCommandBuilder(parentAdapter);
SqlCommandBuilder childCmdBuilder = new SqlCommandBuilder(childAdapter);
if (ds.HasChanges())
{
ds = ds.GetChanges();
sqlConn.Open();
SqlTransaction sqlTrans = sqlConn.BeginTransaction();
try
{
parentAdapter.SelectCommand.Transaction = sqlTrans;
parentCmdBuilder.GetInsertCommand().Transaction = sqlTrans;
parentAdapter.Update(ds, "Parent");
childAdapter.SelectCommand.Transaction = sqlTrans;
childCmdBuilder.GetInsertCommand().Transaction = sqlTrans;
childAdapter.Update(ds, "Child");
sqlTrans.Commit();
sqlConn.Close();
}
catch (Exception ex)
{
sqlTrans.Rollback();
sqlConn.Close();
Console.WriteLine(ex.Message);
}
}
编辑:我可能为这个问题增加了一层额外的复杂性。通过取出与 SqlTransaction 相关的所有代码,我仍然得到相同的“INSERT 语句与 FOREIGN KEY 约束冲突”错误。