简体   繁体   中英

How to rollback multiple transaction in (C#) ASP.NET and SQL Server

I have a more transaction to insert to sql server. And my transaction it's have a Header & Line Detail my data like this

[
  {

    "orderH_List": {
      "NetAmt": 10512.0,
      "DocType": "PO",
      "DocID": "PO0001900088"

    },

    "orderD_List": [
      {

        "Uom": "EA",
        "Qty": 50,
        "LineID": 1,
        "ItemCode": "1010035",
        "DocID": "PO0001900088"

      },
      {

        "Uom": "EA",
        "Qty": 42,
        "LineID": 2,
        "ItemCode": "1010034",
        "DocID": "PO0001900088"

      } 
    ]
},
{

    "orderH_List": {

      "NetAmt": 10512.0,
      "DocType": "PO",
      "DocID": "PO0001900089"

    },
    "orderD_List": [
      {

        "Uom": "EA",
        "Qty": 42,
        "LineID": 1,
        "ItemCode": "1010034",
        "DocID": "PO0001900089"

      },
      {

        "Uom": "EA",
        "Qty": 22,
        "LineID": 2,
        "ItemCode": "1010035",
        "DocID": "PO0001900089"

      } 
    ]
  } 
]

And then if some row of data has false I want to row back all that transaction.

I try to rollback data but I can't to execute my query if I call DB.Commit() after line detail execute. But if I call DB.commit() after head executes its work.

            for (var x = 0; x < All_Order.Count; x++) {

                JObject OrderHead = (JObject)(All_Order[x]["orderH_List"]);  
                JArray OrderLine = (JArray)(All_Order[x]["orderD_List"]);  

                String connectionString = @"Data Source =xxxxxxx; Integrated Security=false;Persist Security Info=true; User ID=xxxxx; Password=xxxxxx; Initial Catalog=xxxxxx";
                SqlConnection myConnection = new SqlConnection(connectionString);
                myConnection.Open();
                System.Diagnostics.Debug.WriteLine("myConnection : " + myConnection );
                SqlTransaction Trans;
                Trans = myConnection.BeginTransaction(IsolationLevel.ReadCommitted);

                string query2 = "INSERT INTO SF_OrderH ( DocType,DocID,RefDocNo,DocDate,SentDT,BillDT,CusRecDT,BillRetDT,ShipTo,Remark1,Remark2,Status,NetAmt,CreateDT,TransferDT)";
                query2 += "VALUES   ( @DocType, @DocID, @RefDocNo, @DocDate, @SentDT, @BillDT, @CusRecDT, @BillRetDT, @ShipTo, @Remark1, @Remark2, @Status, @NetAmt, @CreateDT, @TransferDT)";
                SqlCommand myCommand2 = new SqlCommand();
                myCommand2.Connection = myConnection;
                myCommand2.Transaction = Trans;
                myCommand2.CommandText = query2;

                try
                {

                        myCommand2.Parameters.AddWithValue("@DocType", (string)OrderHead["DocType"] == null ? null : (string)OrderHead["DocType"]);
                        myCommand2.Parameters.AddWithValue("@DocID", (string)OrderHead["DocID"] == null ? null : (string)OrderHead["DocID"]);
                        myCommand2.Parameters.AddWithValue("@RefDocNo", (string)OrderHead["RefDocNo"] == null ? "" : (string)OrderHead["RefDocNo"]);
                        myCommand2.Parameters.AddWithValue("@DocDate", (string)OrderHead["DocDate"] == null ? null : (string)OrderHead["DocDate"]);
                        myCommand2.Parameters.AddWithValue("@SentDT", DateTime.Parse((string)OrderHead["SentDT"]));  
                        myCommand2.Parameters.AddWithValue("@BillDT", DateTime.Parse((string)OrderHead["BillDT"])); 
                        myCommand2.Parameters.AddWithValue("@CusRecDT", DateTime.Parse((string)OrderHead["CusRecDT"])); 
                        myCommand2.Parameters.AddWithValue("@BillRetDT", DateTime.Parse((string)OrderHead["BillRetDT"]));  
                        myCommand2.Parameters.AddWithValue("@ShipTo", (string)OrderHead["ShipTo"] == null ? null : (string)OrderHead["ShipTo"]);
                        myCommand2.Parameters.AddWithValue("@Remark1", (string)OrderHead["Remark1"] == null ? "" : (string)OrderHead["Remark1"]);
                        myCommand2.Parameters.AddWithValue("@Remark2", (string)OrderHead["Remark2"] == null ? "" : (string)OrderHead["Remark2"]);
                        myCommand2.Parameters.AddWithValue("@Status", (string)OrderHead["Status"] == null ? "" : (string)OrderHead["Status"]);
                        myCommand2.Parameters.AddWithValue("@NetAmt", (double)OrderHead["NetAmt"] == null ? 0 : (double)OrderHead["NetAmt"]);
                        myCommand2.Parameters.AddWithValue("@CreateDT", DateTime.Now);
                        myCommand2.Parameters.AddWithValue("@TransferDT", DateTime.Now);  
                        myCommand2.CommandType = CommandType.Text;
                        myCommand2.ExecuteNonQuery();
                        //Trans.Commit(); *** if i commit() on this position it's work!!!    


                    for (var i = 0; i < OrderLine.Count; i++)
                    {
                        string query = "INSERT INTO SF_OrderD ( DocType, DocID, LineID, ItemCode, Qty, Uom, IsFree, ProfitID, NetAmt )";
                        query += "VALUES   ( @DocType, @DocID, @LineID, @ItemCode, @Qty, @Uom, @IsFree, @ProfitID, @NetAmt )";
                        SqlCommand myCommand = new SqlCommand(query, myConnection);

                        myCommand.Parameters.AddWithValue("@DocType", (string)OrderLine[i]["DocType"] == null ? null : (string)OrderLine[i]["DocType"]);
                        myCommand.Parameters.AddWithValue("@DocID", (string)OrderLine[i]["DocID"] == null ? null : (string)OrderLine[i]["DocID"]);
                        myCommand.Parameters.AddWithValue("@LineID", (int)OrderLine[i]["LineID"] == null ? 0 : (int)OrderLine[i]["LineID"]);
                        myCommand.Parameters.AddWithValue("@ItemCode", (string)OrderLine[i]["ItemCode"] == "" ? null : (string)OrderLine[i]["ItemCode"]);
                        myCommand.Parameters.AddWithValue("@Qty", (int)OrderLine[i]["Qty"] == null ? 0 : (int)OrderLine[i]["Qty"]);
                        myCommand.Parameters.AddWithValue("@Uom", (string)OrderLine[i]["Uom"] == null ? "" : (string)OrderLine[i]["Uom"]);
                        myCommand.Parameters.AddWithValue("@IsFree", (string)OrderLine[i]["IsFree"] == null ? "" : (string)OrderLine[i]["IsFree"]);
                        myCommand.Parameters.AddWithValue("@ProfitID", (string)OrderLine[i]["ProfitID"] == null ? "" : (string)OrderLine[i]["ProfitID"]);
                        myCommand.Parameters.AddWithValue("@NetAmt", (int)OrderLine[i]["NetAmt"] == null ? 0 : (int)OrderLine[i]["NetAmt"]);
                        myCommand.ExecuteNonQuery();

                        System.Diagnostics.Debug.Write("INSERT LINE TO SQL COMPLETE!");
                    }
                    Trans.Commit(); // *** if i commit() on this position it's error
                }
                catch (Exception ex)
                {
                    Trans.Rollback();
                }
            }

* * My Error Message

System.InvalidOperationException: ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized. at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at SaleForceAPI.Controllers.GetSaleForce_AccountController.GetSFTokens(String Type) in C:\\Users\\Administrator\\source\\repos\\SaleForceAPI\\SaleForceAPI\\Controllers\\GetSaleForce_AccountController.cs:line 232

and

ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.

** Line 232 is myCommand.ExecuteNonQuery();

I'm not totally sure what goes wrong with your code. But try restructurizing it like this and it should work:

using (SqlConnection conn = new SqlConnection(@"Data Source =xxxxxxx; Integrated Security=false;Persist Security Info=true; User ID=xxxxx; Password=xxxxxx; Initial Catalog=xxxxxx"))
{
    conn.Open();

    using (SqlTransaction trans = conn.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
    {
        try 
        {
            string query = <Define your inserts here>;
            SqlCommand cmd = new SqlCommand(query, conn, trans);
            cmd.ExecuteNonQuery();

            trans.Commit();
        }
        catch(Exception ex) 
        { 
            trans.Rollback();    
        }
     }

    conn.Close();
}

You forgot to assign the Transaction object to your newly created SQLCommand "myCommand". Try this before executing your query

...
myCommand.Transaction = Trans;
myCommand.ExecuteNonQuery();
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM