1、框架级事务处理方式。
会默认创建本地轻量级别的事务范围环境,会给事务环境中所有方法调用添加同一个事务连接。如果在环境范围内有多个连接被打开,那么它会启用分布式事务,增加性能负载。会产生DTS通讯。
2、企业级别库
数据访问块的每个方法调用会为每个请求打开并关闭连接。那么如果利用TransactionScope来包含多个方法调用。那么默认将启用DTS事务处理。增加性能负载。
3、企业级别库已经考虑到这点,如果在范围内,则内部利用getOpenConnection来代替getConnection
When you have finished using the reader, the best practice is to close this connection. However, if you are using an instance of TransactionScope, you must not do this because closing this connection and creating a new connection changes the lightweight transaction to a distributed transaction.
4、用户事务管理
Use the CommandBehavior.CloseConnection paremeter when you call the ExecuteReader method. This closes the connection when the DataReader is closed. If you use ExecuteReader within a try block, you should add a finally statement and close the returned DataReader object, as shown in the following example.
using (IDataReader reader = db.ExecuteReader(cmd))
{
// Process results
}
5、
public bool Transfer(int transactionAmount, int sourceAccount, int destinationAccount)
{
bool result = false;
// Create the database object, using the default database service. The
// default database service is determined through configuration.
Database db = DatabaseFactory.CreateDatabase();
// Two operations: one to credit an account and one to debit another account.
string sql = "CreditAccount";
DbCommand creditCommand = db.GetStoredProcCommand(sql);
db.AddInParameter(creditCommand, "AccountID", DbType.Int32, sourceAccount);
db.AddInParameter(creditCommand, "Amount", DbType.Int32, transactionAmount);
sql = "DebitAccount";
DbCommand debitCommand = db.GetStoredProcCommand(sql);
db.AddInParameter(debitCommand, "AccountID", DbType.Int32, destinationAccount);
db.AddInParameter(debitCommand, "Amount", DbType.Int32, transactionAmount);
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
try
{
// Credit the first account.
db.ExecuteNonQuery(creditCommand, trans);
// Debit the second account.
db.ExecuteNonQuery(debitCommand, trans);
// Commit the transaction.
trans.Commit();
result = true;
}
catch
{
// Roll back the transaction.
trans.Rollback();
}
conn.Close();
return result;
}
}