如何在更新时将更新级联到相关的DataRow对象
本文关键字:更新 DataRow 对象 级联 | 更新日期: 2023-09-27 18:20:46
我一直在努力让我的SqlDataAdapters协同工作,通过单个SQL事务将一行插入父表和子表。我似乎无法从父表中获得要级联到子表的ID。
我使用的是MSSQL 2012。我已经在dbo.parentID和dbo.childparent_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约束冲突"错误。
您想添加此行:
ds.Tables["Child"].Constraints.Add(
new ForeignKeyConstraint(
ds.Tables["Parent"].Columns["id"],
ds.Tables["Child"].Columns["parent_id"]
)
);
请参阅,尽管您在数据库级别设置了这些约束,但您需要构建此约束,以便id
字段在从数据库返回后级联到parent_id
字段。