我一直在苦苦思索,试图让我的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相关的所有代码,我仍然得到相同的“与FOREIGN KEY约束冲突的INSERT语句”错误。
答案 0 :(得分:1)
您想要添加以下这一行:
ds.Tables["Child"].Constraints.Add(
new ForeignKeyConstraint(
ds.Tables["Parent"].Columns["id"],
ds.Tables["Child"].Columns["parent_id"]
)
);
请参阅,虽然您在数据库级别设置了这些约束,但您需要构建此约束,以便id
字段级联后向下到parent_id
字段它从数据库中返回。