简体   繁体   English

如何在(C#)ASP.NET和SQL Server中回滚多个事务

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

I have a more transaction to insert to sql server. 我有更多事务要插入到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. 然后,如果某行数据​​为false,我想回退所有该事务。

I try to rollback data but I can't to execute my query if I call DB.Commit() after line detail execute. 我尝试回滚数据,但是如果在执行行详细信息之后调用DB.Commit(),则无法执行查询。 But if I call DB.commit() after head executes its work. 但是,如果我在head执行工作后调用DB.commit()。

            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. System.InvalidOperationException:当分配给命令的连接处于暂挂的本地事务中时,ExecuteNonQuery要求该命令具有事务。 The Transaction property of the command has not been initialized. 该命令的Transaction属性尚未初始化。 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 在System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1完成,System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1完成,String methodName,布尔sendToPipe,Int32超时,布尔值和usedCache,布尔值asyncWrite,布尔值inRetry处) )在System.Data.SqlClient.SqlCommand.ExecuteNonQuery()在SaleForceAPI.Controllers.GetSaleForce_AccountController.GetSFTokens(String Type)在C:\\ Users \\ Administrator \\ source \\ repos \\ SaleForceAPI \\ SaleForceAPI \\ Controllers \\ GetSaleForce_AccountController.cs:线232

and

ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. 当分配给该命令的连接处于未决本地事务中时,ExecuteNonQuery要求该命令具有事务。 The Transaction property of the command has not been initialized. 该命令的Transaction属性尚未初始化。

** Line 232 is myCommand.ExecuteNonQuery(); **第232行是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". 您忘记将事务对象分配给新创建的SQLCommand“ myCommand”。 Try this before executing your query 在执行查询之前尝试一下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Asp.Net MVC中的多个页面请求之间使用单个Sql Server事务 - How to use a single Sql Server Transaction between multiple page requests in Asp.Net MVC 动态sql和sql的多个搜索条件中的问题加入asp.net c#sql server - problem in multiple search criteria with dynamic sql and sql joins asp.net c# sql server SQL Server,C#:事务回滚的超时异常 - SQL Server, C#: Timeout exception on Transaction Rollback 使用C#将SQL Server 2008中的多个SQL查询合并到ASP.NET上的数据表中 - Combine multiple SQL queries in SQL Server 2008 into a datatable on ASP.NET using C# 如何在asp.net mvc C#中使用paypal交易的交易ID获取交易详情? - How to get transaction details using transaction ID of a paypal transaction in asp.net mvc C#? .NET+SQL Server 2005 - 如何回滚事务但保留日志 - .NET+SQL Server 2005 - How to rollback transaction but keep the log ASP.NET MVC / C#/ SQL Server应用程序:多个用户同时更新表的问题 - ASP.NET MVC / C# / SQL Server Application : Issue with multiple users updating a table same time 使用C#从SQL Server中的单个表在ASP.NET中创建多个RadioButtonLists - Create multiple RadioButtonLists in ASP.NET from a single table in SQL Server using C# asp.net项目C#,SQL Server,插入不起作用 - asp.net project C#, SQL server, Insert is not working ASP.NET C#在SQL Server数据库表中搜索 - ASP.NET C# Search in a SQL Server Database Table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM