Click here to Skip to main content
13,139,569 members (54,025 online)
Click here to Skip to main content
Add your own
alternative version

Stats

13.7K views
148 downloads
17 bookmarked
Posted 9 Sep 2014

Simple Unit of Work Design Pattern

, 9 Sep 2014
Rate this:
Please Sign up or sign in to vote.
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

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

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

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.

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)

Share

About the Author


You may also be interested in...

Pro

Comments and Discussions

 
GeneralMy vote of 5 Pin
srilekhamenon29-Oct-14 22:52
membersrilekhamenon29-Oct-14 22:52 
GeneralMy vote of 3 Pin
Sinisa Hajnal11-Sep-14 20:28
memberSinisa Hajnal11-Sep-14 20:28 
QuestionCleanup after commit? Pin
musketier10-Sep-14 22:35
membermusketier10-Sep-14 22:35 
AnswerRe: Cleanup after commit? Pin
Ravindra T C11-Sep-14 5:18
memberRavindra T C11-Sep-14 5:18 
GeneralRe: Cleanup after commit? Pin
Sinisa Hajnal11-Sep-14 20:26
memberSinisa Hajnal11-Sep-14 20:26 
Questiondraft ? Pin
123mel10-Sep-14 22:00
member123mel10-Sep-14 22:00 
AnswerRe: draft ? Pin
Ravindra T C11-Sep-14 5:17
memberRavindra T C11-Sep-14 5:17 
GeneralMy vote of 5 Pin
Member 1099748610-Sep-14 18:55
memberMember 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
memberHumayun 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170915.1 | Last Updated 9 Sep 2014
Article Copyright 2014 by Ravindra T C
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid