TransactionScope

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;
  }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值