Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Simple Unit of Work Design Pattern

4.63/5 (10 votes)
9 Sep 2014CPOL1 min read 26.2K   185  
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)