Editorials

Unit of Work

What is a Unit Of Work? If you’re new to working with any sort of data storage, this is a very important question. The answer to this question is essential to your success when persisting data to any kind of storage. Some storage engines make it easier than others. So, let’s start out with an understanding of what a Unit of Work entails.

When persisting data to any storage engine, a Unit Of Work is the combination of all data that must persist successfully in order to be complete. A good example would be the saving of a customer with a shopping cart for an online store. If the shopping cart data is saved, but the customer data is not, the shopping cart data has no value. All of the customer data and the shopping cart, and the chosen items in the cart, must be saved successfully in order to be a complete Unit of Work.

With SQL data storage, depending on how your database is configured, you can encapsulate a unit of work inside a database transaction. If anything goes wrong while data is being inserted, updated and/or deleted, the transaction can be rolled back, and all modifications are lost. This transactional capability can be used to implement a Unit of Work. In this case, everythiing saves, or nothing saves.

So, to be clear, a transaction is not a Unit of Work. It can be used to implement a Unit of Work. A Unit of Work is a business requirement that may be implemented by a database transaction. If you are working with a different kind of storage you can use different transaction implementations.

Even if you are using an SQL engine, you can still implement a Unit of Work outside of the database. Many ORM frameworks allow you to implement a Unit of Work inside the framework instead of directly in the database. This allows you to still use the Unit of Work pattern when writing to more than one data store, even if they are all SQL. Doing the Unit of Work outside of the database may add a little more overhead, but it provides a lot of flexibility in the things you can accomplish.

So, for those of you learning to do data persistence, learn to think in terms of a Unit of Work. Learning to master the Unit of Work pattern will save you hours of grief.

Do you have a favorite way to implement the Unit of Work pattern? Share your favorites in our comments.

Cheers,

Ben