我有一个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 ... –