views:

111

answers:

3

In layman's terms, what is a unit of work in regards to database objects? I'm researching how to convert database tables into C# classes and I frequently come across this term, but everyone seems to describe it as if you should already know what it is.

+2  A: 

I'll quote Martin Fowler here, since I think his meaning is one of the clearest, most comprehensible I've seen:

A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.

Reed Copsey
Thanks, that was very clear.
Daniel T.
+1  A: 

Basically it means the work required to complete an atomic action, e.g. transferring money between two checking accounts.

Example (in pseudocode)

Procedure TransferBetweenAccounts(Amount, Account source, Account target)
   Begin Transaction
      Debit source account By (Amount)   }----Unit of
      Credit target account By (amount)  }----Work 
   End Transaction

   If Transaction Failed
       Roll Back

A good MSDN article describing Unit of Work and Persistence Ignorance is here: http://msdn.microsoft.com/en-us/magazine/dd882510.aspx

Robert Harvey
A: 

In LINQ to SQL a unit of work is defined as (http://msdn.microsoft.com/en-us/library/bb546187.aspx):

An instance of a data context should have a lifetime of one "unit of work." In a loosely-coupled environment, a unit of work is typically small, perhaps one optimistic transaction, including a single call to SubmitChanges. Therefore, the data context is created and disposed at method scope. If the unit of work includes calls to business rules logic, then generally you will want to keep the DataContext instance for that whole operation

Understanding the unit of work is important for success with LINQ to SQL. Have a look at this page (A update scenario), for how the unit of work pattern fits into LINQ to SQL:

http://aspalliance.com/1414_LINQ_to_SQL_Part_4__Updating_our_Database.3

Martin Fowler's Patterns of Enterprise Architecture book has quite a few pages devoted to the topic (pg 184-194). His brief definition is:

"Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems."

RichardOD