Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C#
Tip/Trick

Simple Unit of Work Design Pattern

Rate me:
Please Sign up or sign in to vote.
4.63/5 (10 votes)
9 Sep 2014CPOL1 min read 25.2K   185   15   10
Simple Unit of Work Design Pattern

Introduction

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

When you are pulling data out of the database, it’s important to keep track of what you have changed otherwise data won’t be written back into the database. Similarly, you have to insert new objects you create and remove any objects you delete.

Advantages of Unit of Work Pattern

Unit of Work pattern first will maintain in-line memory updates and second it will send all in-line memory updates to the database in a single transaction.

Below are the two steps to achieve the goal:

  • It will maintain lists of business objects in in-line memory which have been modified during the transaction.
  • When transaction is completed, all these updates are sent as one unit of work to be persisted physically in a database in one go.

Sample C# Unit of Work Code

Step 1: Create a Interface (IEntity) for business objects

C#
public interface IEntity
    {
        int EmployeeId { get; set; }
        string EmployeeName { get; set; }
        string Address { get; set; }
        string Email { get; set; }
        void Insert();
    }

Step 2: Implement the Interface to Employee object

C#
public class Employee : IEntity
    {
        EmployeeDb employeeDb = new EmployeeDb();
        private int employeeId = 0;
        public int EmployeeId
        {
            get { return employeeId; }
            set { employeeId = value; }
        }

        private string employeeName = string.Empty;
        public string EmployeeName
        {
            get { return employeeName; }
            set { employeeName = value; }
        }

        private string address = string.Empty;
        public string Address
        {
            get { return address; }
            set { address = value; }
        }

        private string email = string.Empty;
        public string Email
        {
            get { return email; }
            set { email = value; }
        }
        public void Insert()
        {
            employeeDb.InsertTransactionToDb(EmployeeId, EmployeeName, Address, Email);
        }

Step 3: Create a Unit of Work Object

C#
public class UnitOfWork
    {
       private readonly List<IEntity> _newEmployee=new List<IEntity>();
       public void Add(IEntity emp)
       {
           _newEmployee.Add(emp);
       }
       public void Commit()
       {
           using (TransactionScope scope = new TransactionScope())
           {
               foreach (IEntity entity in _newEmployee)
               {
                   entity.Insert();
               }
               scope.Complete();
           }
       }
    }

Step 4: Result

On the client side, we can create Employee object, add business objects to the in-line memory, and finally all these modifications are sent in an atomic manner to the database by calling the commit method.

C#
static void Main(string[] args)
        {
            Employee _employee = new Employee(); // 1st Record of Employee.
            _employee.EmployeeId = 1;
            _employee.EmployeeName = "Pradeep";
            _employee.Address = "Mumbai";
            _employee.Email = "pradeep.p@hotmail.com";

            Employee _emp = new Employee(); // Second Record of Employee.
            _emp.EmployeeId = 2;
            _emp.EmployeeName = "Mahesh";
            _emp.Address = "Bangalore";
            _emp.Email = "mahesh.g@hotmail.com";

            UnitOfWork _unitOfWork = new UnitOfWork();
            _unitOfWork.Add(_employee); // 1st record added to inline memory.
            _unitOfWork.Add(_emp); // 2nd record added to inline meomory.
            _unitOfWork.Commit(); // The full final inline memory collection sent to final commit.
        }

Note: I have not added the database logic here, you can find the full source code of this unit of work pattern in the attachment.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralMy vote of 5 Pin
srilekhamenon29-Oct-14 22:52
professionalsrilekhamenon29-Oct-14 22:52 
Good Work
GeneralMy vote of 3 Pin
Sinisa Hajnal11-Sep-14 20:28
professionalSinisa Hajnal11-Sep-14 20:28 
QuestionCleanup after commit? Pin
musketier10-Sep-14 22:35
musketier10-Sep-14 22:35 
AnswerRe: Cleanup after commit? Pin
Ravindra T C11-Sep-14 5:18
professionalRavindra T C11-Sep-14 5:18 
GeneralRe: Cleanup after commit? Pin
Sinisa Hajnal11-Sep-14 20:26
professionalSinisa Hajnal11-Sep-14 20:26 
Questiondraft ? Pin
123mel10-Sep-14 22:00
123mel10-Sep-14 22:00 
AnswerRe: draft ? Pin
Ravindra T C11-Sep-14 5:17
professionalRavindra T C11-Sep-14 5:17 
GeneralMy vote of 5 Pin
Member 1099748610-Sep-14 18:55
Member 1099748610-Sep-14 18:55 
GeneralMy vote of 5 Pin
Nandakishore G N10-Sep-14 2:24
professionalNandakishore G N10-Sep-14 2:24 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun9-Sep-14 21:05
Humayun Kabir Mamun9-Sep-14 21:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.