![](/img/trans.png)
[英]How to use a single Sql Server Transaction between multiple page requests in Asp.Net MVC
[英]How to rollback multiple transaction in (C#) ASP.NET and SQL Server
我有更多事務要插入到SQL Server。 我的交易有一個標題和行詳細信息,我的數據是這樣的
[
{
"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"
}
]
}
]
然后,如果某行數據為false,我想回退所有該事務。
我嘗試回滾數據,但是如果在執行行詳細信息之后調用DB.Commit(),則無法執行查詢。 但是,如果我在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();
}
}
* *我的錯誤信息
System.InvalidOperationException:當分配給命令的連接處於暫掛的本地事務中時,ExecuteNonQuery要求該命令具有事務。 該命令的Transaction屬性尚未初始化。 在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
和
當分配給該命令的連接處於未決本地事務中時,ExecuteNonQuery要求該命令具有事務。 該命令的Transaction屬性尚未初始化。
**第232行是myCommand.ExecuteNonQuery();
我不太確定您的代碼出了什么問題。 但是嘗試像這樣進行重組,它應該可以工作:
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();
}
您忘記將事務對象分配給新創建的SQLCommand“ myCommand”。 在執行查詢之前嘗試一下
...
myCommand.Transaction = Trans;
myCommand.ExecuteNonQuery();
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.