public
bool
Transfer(
int
transactionAmount,
int
sourceAccount,
int
destinationAccount)
{
bool
result
=
false
;
//
CreatetheDatabaseobject,usingthedefaultdatabaseservice.The
//
defaultdatabaseserviceisdeterminedthroughconfiguration.
Databasedb
=
DatabaseFactory.CreateDatabase();
//
Twooperations,onetocreditanaccount,andonetodebitanother
//
account.
string
sqlCommand
=
"
CreditAccount
"
;
DBCommandWrappercreditCommandWrapper
=
db.GetStoredProcCommandWrapper(sqlCommand);
creditCommandWrapper.AddInParameter(
"
@AccountID
"
,DbType.Int32,sourceAccount);
creditCommandWrapper.AddInParameter(
"
@Amount
"
,DbType.Int32,transactionAmount);
sqlCommand
=
"
DebitAccount
"
;
DBCommandWrapperdebitCommandWrapper
=
db.GetStoredProcCommandWrapper(sqlCommand);
debitCommandWrapper.AddInParameter(
"
@AccountID
"
,DbType.Int32,destinationAccount);
debitCommandWrapper.AddInParameter(
"
@Amount
"
,DbType.Int32,transactionAmount);
using
(IDbConnectionconnection
=
db.GetConnection())
{
connection.Open();
IDbTransactiontransaction
=
connection.BeginTransaction();
try
{
//
Creditthefirstaccount
db.ExecuteNonQuery(creditCommandWrapper,transaction);
//
Debitthesecondaccount
db.ExecuteNonQuery(debitCommandWrapper,transaction);
//
Committhetransaction
transaction.Commit();
result
=
true
;
}
catch
{
//
Rollbacktransaction
transaction.Rollback();
}
connection.Close();
return
result;
}
在这段例子代码中,其核心就是关于 IDbTransaction的使用。