5.5. Working with Connection and Transactions

The DaoManager provides methods for working with connection and transaction. These methods allow you to demarcate connection/transactions and avoid having to pass transaction objects, like IDbTransaction, around to all of your DAOs.

Example 5.6. Example DAO transaction management

[C#]
Product p1 = new Product();
Product p2 = new Product();
Category c 1= new Category()
c1.Add(p1);
c2.Add(p2);

IDaoManager daoManager = DaoManager.GetInstance("PetStore"); 
ICategoryDao categoryDao = daoManager[typeof(ICategoryDao)] as ICategoryDao;
IProductDao productDao = daoManager[typeof(IProductDao)] as IProductDao;

try {
      daoManager.BeginTransaction();
      productDao.Insert(p1);
      productDao.Insert(p2);
      categoryDao.Insert(c1);
      daoManager.CommitTransaction();
}
catch {
        daoManager.RollBackTransaction();
}

Calling BeginTransaction() lets the DaoManager know that you are interested in managing transactions programmatically. It is very important that you guarantee a call to RollBackTransaction() if you’ve called BeginTransaction(), which is why it is within the catch block. The call to RollBackTransaction() will rollback any changes you’ve made in case an exception is thrown before the call to CommitTransaction(). Be aware that if an exception occurs before BeginTransaction() completes and is caught in the catch block, RollBackTransaction() will also throw another exception since a transaction was not started.

When you deal with a connection and transaction, you can also use the using syntax as in the examples below.

[C#]
IDaoManager daoManager = DaoManager.GetInstance("PetStore"); 
IAccountDao accountDao = daoManager[typeof(IAccountDao)] as IAccountDao;

using ( IDalSession session = daoManager.OpenConnection() )
{
   Account account = NewAccount();
   accountDao.Create(account);
}

using ( IDalSession session = daoManager.BeginTransaction() )
{
   Account account = NewAccount();
   Account account2 = accountDao.GetAccountById(1);
   account2.EmailAddress = "someotherAddress@somewhere.com";

   accountDao.Create(account);
   accountDao.Update(account2);

   session.Complete(); // Commit
}