Participating In A Transaction

Sometimes it will be necessary for two or more adapters to participate in a transaction. You can do this by leveraging either the overloaded adapter constructor or the AttachTransaction() method of the adapter.

This example illustrates the use of a SqlTransaction to insert an order and its items into a database:

   1:  private static void SaveOrder(Order order) {
   2:      using (SqlConnection connection = new SqlConnection(ApplicationState.ConnectionString)) {
   3:          connection.Open();
   4:          SqlTransaction transaction = connection.BeginTransaction();
   5:   
   6:          try {
   7:              using (InsertOrderAdapter orderAdapter = new InsertOrderAdapter(transaction)) {
   8:                  orderAdapter.CustomerId = order.Customer.PrimaryKey;
   9:                  orderAdapter.OrderNumber = order.OrderNumber;
  10:                  orderAdapter.TotalAmount = order.TotalPrice;
  11:                  orderAdapter.Execute();
  12:   
  13:                  order.PrimaryKey = orderAdapter.OrderId;
  14:              }
  15:   
  16:              foreach (OrderItem item in order.Items) {
  17:                  using (InsertOrderItemAdapter orderItemAdapter = new InsertOrderItemAdapter(transaction)) {
  18:                      orderItemAdapter.OrderId = order.PrimaryKey;
  19:                      orderItemAdapter.FileId = item.Asset.PrimaryKey;
  20:                      orderItemAdapter.Quantity = item.Quantity;
  21:                      orderItemAdapter.ItemPrice = item.Asset.Price;
  22:                      orderItemAdapter.Execute();
  23:                  }
  24:              }
  25:   
  26:              transaction.Commit();
  27:          } catch {
  28:              transaction.Rollback();
  29:              throw;
  30:          }
  31:      }
  32:  }