我正在尝试使用TransactionScope
对象了解事务如何在c#中工作。我在SQL服务器上了解它们,但我不知道如何在c#
中验证这一点。例如,我想检查是否将IsolationLevel
设置为ReadUnCommitted
,如何在我的代码中验证此行为?
目前这是我的简单代码,我想测试的是在我的第一个Update
命令正在执行而未提交/回滚时如何验证其他事务是否能够读取它影响的数据?任何人都可以帮我一个代码示例吗?
这是我的代码:
public void TransferAmount(Account a)
{
bool debit = false;
bool credit= true;
var option = new TransactionOptions();
option.IsolationLevel = System.Transactions.IsolationLevel.ReadUnCommitted;
try
{
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, option))
{
using (IDbCommand cmd = Idbconnection.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_Update_Debit";
IDataParameter param = cmd.CreateParameter();
param.ParameterName = "@mDebitAmount";
param.Value = a.Amount;
cmd.Parameters.Add(param);
Idbconnection.Open();
debit = cmd.ExecuteNonQuery() == 1;
}
using (IDbCommand cmd = Idbconnection.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_Update_Credit";
IDataParameter param = cmd.CreateParameter();
param.ParameterName = "@mCreditAmount";
param.Value = a.Amount;
cmd.Parameters.Add(param);
credit = cmd.ExecuteNonQuery() == 1;
}
if (debit == credit)
transactionScope.Complete();
}
}
catch (Exception ex)
{
System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
throw new FaultException(new FaultReason(new FaultReasonText(ex.Message)));
}
}