Transactional Data Persistence with OpenAccess

OpenAccess is an Object Relational Mapper (ORM) from Telerik, and as you might have noticed from my earlier post about building an OpenAccess enabled project on a build server, I am currently working with OpenAccess on one of my projects. I figure that since I am using this Object Relational Mapper that I should post regularly about using it so that others starting to use OpenAccess have a shorter learning curve.

Making modifications to persisted data needs to be done transactionally so that any issues which arise during the persistence can be responded to and handled correctly. For example if you are going to be updating a customer and that customer’s address then you will want to make sure that the save is an all or nothing situation since it could be bad if the address was saved but not the customer. With a transaction you have the ability to rollback so that you can be at the initial state once again. By doing this we can then handle the error and not have the transaction halfway committed.

OpenAccess has support for transactions using its ObjectScope. To begin a transaction you simply need to access the Transaction peroperty of the IObjectScope and call its Begin method. To complete the transaction you call the Transaction’s Commit method.

using (IObjectScope objectScope = MyScopeProvider.GetNewObjectScope())
{
    objectScope.Transaction.Begin();
    // Perform the persistence logic here
    objectScope.Transaction.Commit();
}

So this is pretty easy, right? Well what about rolling back the transaction if we have a problem. So the simple thing to do is to wrap a try-catch block around the transaction. Then in the catch portion we will need to make sure that if the transaction is still active that we roll everything back to the previous state. (We also handle the exception, but that’s your job not mine.)

using (IObjectScope objectScope = MyScopeProvider.GetNewObjectScope())
{
    try
    {
        objectScope.Transaction.Begin();
        // Perform the persistence logic here
        objectScope.Transaction.Commit();
    }
    catch
    {
        // UPDATE: This explicit rollback is only
        // required if you're crazy and don't trust
        // that things will wrap up nicely on their own.
        if (objectScope.Transaction.IsActive) 
            objectScope.Transaction.Rollback();
 
        // Make sure you handle the exception here
        // failing silently is often a problem
    }
}

So all we did is check to see if the Transaction is Active and if it is still active rollback the transaction. Wasn’t that easy?

Comments