我有一個WPF應用程序,並且在按鈕單擊事件中我調用了WCF服務來處理它中的事務。一次交易完成後,我拋出異常。查看事務是否會回滾。但即使我得到錯誤仍然交易完成它不會在數據庫中止。如何處理WCF服務中的事務
UI按鈕事件:
private void button1_Click(object sender, RoutedEventArgs e)
{
binding = new WSHttpBinding();
endpoint = new EndpointAddress("http://localhost:6144/EmployeeService.svc/EmployeeService");
ChannelFactory<IEmployeeService> cf = new ChannelFactory<IEmployeeService>(binding, endpoint);
IEmployeeService obj = cf.CreateChannel();
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
{
try
{
obj.UpdateProductData(201, 10);
throw new Exception("Wrong");
obj.UpdateProductData(202, 15);
ts.Complete();
}
catch (Exception ex)
{
ts.Dispose();
}
}
}
在app.config中,我已經給出"transactionFlow="true"
。
WCF服務:
[OperationBehavior(TransactionScopeRequired=true,TransactionAutoComplete=true)]
public bool UpdateProductData(int ProdId, int Amount)
{
DALClass objDALProd = new DALClass();
return objDALProd.UpdateProductData(ProdId, Amount);
}
DALClass:
public bool UpdateProductData(int prodID,int Amount)
{
try
{
objComd.Connection = objConn;
objConn.Open();
objComd.CommandText = "UpdateEmployeeData";
objComd.CommandType = CommandType.StoredProcedure;
objParam = new SqlParameter("@ProductId", prodID);
objComd.Parameters.Add(objParam);
objParam = new SqlParameter("@Amount", Amount);
objComd.Parameters.Add(objParam);
objComd.ExecuteNonQuery();
objConn.Close();
}
catch(Exception ex)
{
throw new FaultException("Database Error");
}
return true;
}
請讓我知道我的錯誤是。事務不會回滾,即使當我提出異常時,第一個事務也不會回滾。
注意:您不需要'try/catch/ts.Dispose()'部分。這就是'use'塊本身的用途。更糟的是,你吞下所有的例外。 –
嘗試TransactionAutoComplete = false ... –