Does anyone know how can I all data rollback in .net c# if one of the stored proc failed during the process?
Example:
protected void btnSave_Click(object sender, EventArgs e)
{
int ixTest= SaveTest("123");
CreateTest(ixTest);
}
protected int SaveTest(int ixTestID)
{
SubSonic.StoredProcedure sp = Db.SPs.TestInsert(
null,
ixTestID);
sp.Execute();
int ixTest= (int)sp.OutputValues[0];
return ixTest;
}
private long CreateTest(int ixTest)
{
long ixTestCustomer = CreateTestCustomer();
TestCustomer testCustomer= new TestCustomer();
try
{
testCustomer.TestCustomerId = ixTest;
testCust开发者_如何学JAVAomer.InteractionId = ixTestCustomer ;
testCustomer.Save();
}
catch
{
Response.Redirect("pgCallSaveFailure.aspx");
}
m_saleDetail = new TestSaleDetail();
try
{
m_saleDetail.SaleId = sale.SaleId;
m_saleDetail.Save();
}
catch
{
Response.Redirect("pgCallSaveFailure.aspx");
}
return ixTestCustomer ;
}
I have the following code will call to btnSave_Click, then it will call to another 2 function Savetest() and CreateTest() to save data into the database. How can I rollback all data transaction in the following code if issue only happened in CreateTest() and which Savetest() have run successfully. How can I rollback all data for both Savetest() and CreateTest()?
Use the TransactionScope class
Code performs exact is given below. Hope you can get the idea.
public void SaveData()
{
SqlConnection connDB = new SqlConnection();
SqlCommand cmdExecuting = new SqlCommand();
try {
connDB = new SqlConnection(connection_string);
cmdExecuting.Connection = connDB;
connDB.Open();
cmdExecuting.Transaction = connDB.BeginTransaction();
int result = 0;
result = Method1(cmdExecuting);
if (result != 0) {
cmdExecuting.Transaction.Rollback();
return;
}
result = Method2(cmdExecuting);
if (result != 0) {
cmdExecuting.Transaction.Rollback();
return;
}
cmdExecuting.Transaction.Commit();
} catch (Exception ex) {
cmdExecuting.Transaction.Rollback();
} finally {
cmdExecuting.Dispose();
cmdExecuting = null;
connDB.Close();
connDB = null;
}
}
public int Method1(SqlCommand cmdExecuting)
{
cmdExecuting.Parameters.Clear();
cmdExecuting.CommandText = "stored proc 01";
cmdExecuting.CommandType = CommandType.StoredProcedure;
cmdExecuting.Parameters.Add("@para1", SqlDbType.Int);
cmdExecuting.Parameters("@para1").Value = value;
return cmdExecuting.ExecuteScalar();
}
public int Method2(SqlCommand cmdExecuting)
{
cmdExecuting.Parameters.Clear();
cmdExecuting.CommandText = "stored proc 02";
cmdExecuting.CommandType = CommandType.StoredProcedure;
cmdExecuting.Parameters.Add("@para1", SqlDbType.Int);
cmdExecuting.Parameters("@para1").Value = value;
return cmdExecuting.ExecuteScalar();
}
精彩评论