相关插入在transationscope中失败

时间:2009-09-15 11:15:05

标签: c# transactionscope referential-integrity

我正在使用TransactionScope将对象的数据添加到一个数据库中。

伪代码:

using (TransactionScope trx = new TransactionScope())
{
   SqlConnection con = DL.GetNewConn();
   int newParentRecordID = InsertParentIntoTableA(object parent, con);

   foreach(obj child in parent.childrenObjects)
   {
       child.ParentID = newParentRecordID ;
       int newChildRecordID =  InsertChildIntoTableB(object child, con);
   }
   trx.Complete();
}

我在InsertChildIntoTableB()中遇到异常,错误是TableB中的ParentID在TableA中没有匹配的主键条目。

重用连接。

我如何解决这个问题?在TableA上执行SELECT WITH(NOLOCK)会显示新插入的父记录,但是下面的子记录插入无法看到它。

编辑以澄清:在foreach循环中,我已经有了插入但未通缉的新ParentID。 问题是对子TableB的插入失败,因为TableB中的FK表示父TableA无法看到未提交的新TableA PK ID。

2 个答案:

答案 0 :(得分:0)

如果您有标识列,可以尝试在INSERT语句中使用OUTPUT INSERTED子句。

这是关于此主题的a good article

答案 1 :(得分:0)

附注 - 您必须使用TransactionScope.Complete实例方法显式完成事务,否则它将被回滚。