Tuesday, April 28, 2009

Using Transactions With Business Objects

If your business rule is updating records in multiple database tables then consider using transactions to ensure atomicity of data operations.

Business objects generated by premium projects are not providing an explicit support for transactions and are relying on transaction plumbing available in ADO.NET. Learn more about System.Transaction.TransactionScope to better understand transaction control options available to developers.

Here is a quick example.

Generate a Data Aquarium project from Northwind database and add System.Transactions.dll reference to your project.

image

Enter the following code in your web form code-behind or modify the code appropriately to be used in your business rules.

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyCompany.Data.Objects;
using System.Transactions;

public partial class Demo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        using (TransactionScope trn = new TransactionScope())
        {
            // create a new shipper
            Shippers s = new Shippers();
            s.CompanyName = "Code OnTime";
            s.Phone = "877-467-6340";
            if (s.Insert() != 1)
                throw new Exception("Failed to create a shipper");
            trn.Complete();
        }
    }
}

VB:

Imports System.Collections.Generic
Imports MyCompany.Data.Objects
Imports System.Transactions

Partial Class Demo
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) Handles Me.Load
        ' create a new shipper
        Using trn As TransactionScope = New System.Transactions.TransactionScope()
            Dim s As Shippers = New Shippers()
            s.CompanyName = "Code OnTime"
            s.Phone = "877-467-6340"
            If s.Insert() <> 1 Then
                Throw New Exception("Failed to create a shipper")
            End If
            trn.Complete()
        End Using
    End Sub
End Class

Method Complete will commit all changes.

If an exception is raised then the entire set of changes performed in the scope of transaction prior to the error will be canceled.

No comments:

You can find more about Code OnTime Generator, Data Aquarium Framework, and other great products here.


© 2010 Code OnTime LLC. Intelligent code generation software for ASP.NET. Visit us at http://codeontime.com