我正在尝试创建一个全有或全无的大型transactionScope。我正在插入大约2000条记录。我想插入主键,将其读回然后在事务中插入外键,然后在发生错误时将所有内容回滚。
PSS_InvoiceTotal表有PK - > InvoiceTotalID
PSS_Invoices表具有FK - > InvoiceTotalID
每次创建2个主键行时,问题出现在数据库中。我运行没有外键插入的代码,它工作正常。有没有办法阻止它制作2个主键行?
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
{
try
{
conn.Open();
foreach (var uniqueSupply in supplyList.GroupBy(a=>a.ShipTo))
{
//reset total
total = 0;
var supplyListByShipTo = supplyList.Where(a => a.ShipTo == uniqueSupply.Key);
foreach (var addSupply in supplyListByShipTo)
{
total = total + addSupply.Amount;
}
StringBuilder insert_PSS_InvoiceTotal = new StringBuilder();
//save total to DB
insert_PSS_InvoiceTotal = new StringBuilder();
insert_PSS_InvoiceTotal.Append("INSERT INTO [PSS_InvoiceTotal] ");
insert_PSS_InvoiceTotal.Append("([InvoiceDate],[Amount]) ");
insert_PSS_InvoiceTotal.Append("VALUES(@DateTime, @Amount) ");
insert_PSS_InvoiceTotal.Append("SELECT SCOPE_IDENTITY() AS [InvoiceTotalID];");
cmd = new SqlCommand(insert_PSS_InvoiceTotal.ToString(), conn);
cmd.Parameters.AddWithValue("@DateTime", DateTime.Now);
cmd.Parameters.AddWithValue("@Amount", total);
//ToDo: Add back in later
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
InvoiceTotalID = Convert.ToInt32(dr["InvoiceTotalID"].ToString());
}
dr.Close();
foreach (var supply in supplyListByShipTo)
{
StringBuilder insert_PSS_Invoice = new StringBuilder();
//Create the SQL command
insert_PSS_Invoice.Append("INSERT INTO [PSS_Invoices] ");
insert_PSS_Invoice.Append("([ClientDetailId],Amount],InvoiceTotalId)");
insert_PSS_Invoice.Append("VALUES(");
insert_PSS_Invoice.Append("@Amount,@InvoiceTotalId)");
cmd = new SqlCommand(insert_PSS_Invoice.ToString(), conn);
cmd.Parameters.AddWithValue("@Amount", 4.44);
cmd.Parameters.AddWithValue("@InvoiceTotalId", InvoiceTotalID);
//ToDo: put back in later
cmd.ExecuteNonQuery();
}
}
//Close connection
conn.Close();
//Commit and Dispose Transaction
scope.Complete();
scope.Dispose();
}
catch (Exception ex)
{
//Rollback Transaction
scope.Dispose();
return Json(new { success = false, message = ex.ToString() }, JsonRequestBehavior.AllowGet);
}
}
答案 0 :(得分:0)
尝试发表评论
//ToDo: Add back in later
//cmd.ExecuteNonQuery();
答案 1 :(得分:-1)
您可以考虑使用INSERT命令的OUTPUT选项来获取插入执行的主键。这样你就不必回头了。查看此链接:https://msdn.microsoft.com/en-us/library/ms177564.aspx
此外,您可能需要向命令对象添加输出参数以获取该信息。