0

我的 SQL 事务在 Commit() 上引发异常。这是我第一次将事务与 SqlCommands 一起使用,所以也许我在代码中犯了一些错误。我看到了有关相同错误的其他问题,但没有一个有帮助。我尝试在阅读器上显式调用 Close()但没有用。

using (var selectModifiedCmd = new SqlCommand(selectModified, conn, trans))
                {
                    try
                    {
                        decimal qty, qtyPerUOM, weight, weightKg;
                        string no, binCode, binText, shelfNo, mainZone, sourceTu, destNo, cluster;
                        int lineNo, corridor, sortAsc, sortDesc, rowOrder;
                        short pricePerKg;

                        using (var reader = selectModifiedCmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                               ........

                                using (var updateModifiedCmd = new SqlCommand(updateModified, conn, trans))
                                {
                                    ........

                                    updateModifiedCmd.ExecuteNonQuery();
                                }

                                using (var returnModifiedCmd = new SqlCommand(returnModified, conn, trans))
                                {
                                    returnModifiedCmd.Parameters.AddWithValue("no", no);
                                    returnModifiedCmd.Parameters.AddWithValue("lineNo", lineNo);

                                    returnModifiedCmd.ExecuteNonQuery();
                                }

                                trans.Commit();

                                Globals.WriteLog(MethodBase.GetCurrentMethod().Name, String.Format(logSuccess, no, lineNo, binCode, qty));
                            }
                        }
                    }
                    catch (SqlException ex)
                    {
                        var trace = new StackTrace(ex, true);
                        Globals.WriteLog(
                            MethodBase.GetCurrentMethod().Name,
                            ex.Message + " At line: " + trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber());

                        try
                        {
                            trans.Rollback();
                        }
                        catch (Exception exRollback)
                        {
                            Globals.WriteLog("Rollback error: ", exRollback.Message);
                        }
                    }
                }
4

1 回答 1

0

这要归功于上面评论线程中的 Lasse V. Karlsen,但我希望它也出现在答案中,因为它是答案,有些人不会阅读未回答的问题。

问题是 trans.Commit() 在读者的 using 语句中。需要将它移到 using 语句之外,以便在提交更改之前拆除阅读器。

于 2020-10-15T19:52:40.303 回答