Click here to Skip to main content
16,017,788 members
Articles / Web Development / ASP.NET
Tip/Trick

Understand 3- Tier Architecture in C#

Rate me:
Please Sign up or sign in to vote.
4.35/5 (39 votes)
2 Oct 2013CPOL4 min read 290.4K   49   29
How to

Introduction

In this article we will learn to implement 3- Tier architecture in C#.NET application. 3-Tier architecture is very famous and well known buzz word in world of software development. If we analyze any traditional project then we will find that most of (at least 60-70 %) them has traditional N-Tier, basically 3-Tier architecture. It does not matter whether it is web or windows application, we can implement 3-Tier architecture in any type of environment.

Although it is very well known and common architecture but it’s not very clear to fresher developer or those who are very new in project development.

Why 3-Tier Architecture?

Still I can remember that, the first organization in my career was dealing with one small POS (Point of Sell) project. It was a windows application and there was no layered architecture. We coder people started to write all codes in behind of windows form. Problem started after few days. How? When our manager announced that we have to develop one web version of same product. Again we started to develop web pages from scratch and started to write all code. Totally mess.

So, this is the problem and the solution is tired architecture. If we separate our codes by layer then changes in one layer will not affect much to another one. Tomorrow if business demands, we can change UI very quickly by using existing code.

Difference between Tier and Layer

It is one confusing question for beginner. Few think that both are same. But they are not same. Tier represents different hardware box. Means the components are physically separated to different machines. But in case of layer all component remains in same system.

What are the Layers?

Theoretically it is N-Tier architecture. So, we can create as much layer as possible but basically people classify code in three different categories and put them in three different layers. So, for this article we will consider N-Tier architecture as 3-Tier architecture and try to implement one sample application.

Let’s discuss each and every Layer at first.

Presentation Layer/ UI Layer

This is the top most layer of application where user performs their activity. Let’s take example of any application where user needs to fill up one form. This form is nothing nut presentation layer. In windows application windows form is presentation layer and in web application web form belongs to presentation layer. Basically user’s input validation and rule processing performs in this layer.

Business Layer

This is on top of presentation layer. As the name suggest, most of the business operation performs here. For example, after collecting form data we want to validate them with our custom business rule. Basically we define classes and business entities in this layer.

Data Access Layer

It is on top of Business Logic Layer Data Access Layer presents. It contains methods that helps business layer to connect with database and perform CRUD operation. In data access layer generally all database related code and stuff belongs to. Sometimes people use platform independent data access layer to fetch data from different database vendor.

Let’s Implement

Before start with example one more question need to be clear. How we will pass data from one layer to another layer? Means in which form data from pass?

There are many solutions for this problem. For our example we will pass data through function parameter. In this example we will implement one small windows application to fetch data from database using 3-Tier architecture. In this example we will read data from single "Person" Table.

Code for Data Access Layer

Let’s start from Data access layer; we will create function to read data from database. Have a look on below code.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace WindowsFormsApplication1.DAL
{
    public class PersonDAL
    {
        public string ConString = 
            "Data Source=SOURAV-PC\\SQL_INSTANCE;Initial Catalog=test;Integrated Security=True";
        SqlConnection con = new SqlConnection();
        DataTable dt = new DataTable();
        public DataTable Read()
        {
            con.ConnectionString = ConString;
            if (ConnectionState.Closed == con.State)
                con.Open();
            SqlCommand cmd = new SqlCommand("select * from Person",con);
            try
            {
                SqlDataReader rd = cmd.ExecuteReader();
                dt.Load(rd);
                return dt;
            }
            catch
            {
                throw;
            }
        }
        public DataTable Read(Int16 Id)
        {
            con.ConnectionString = ConString;
            if (ConnectionState.Closed == con.State)
                con.Open();
            SqlCommand cmd = new SqlCommand("select * from Person where ID= "+ Id +"", con);
            try
            {
                SqlDataReader rd = cmd.ExecuteReader();
                dt.Load(rd);
                return dt;
            }
            catch
            {
                throw;
            }
        }
    }
}

We have created two overloaded function to read data. One function will not take any argument and other function will fetch data using ID.

Create Business Logic Layer

Now, we will create Business Logic Layer to communicate with both Presentation layer and Data access layer. Here is our code for Business layer.

C#
using System; using System.Collections.Generic; using System.Data; using WindowsFormsApplication1.DAL;
 
namespace WindowsFormsApplication1.BLL
{
    public class PersonBLL
    {
        public DataTable GetPersons()
        {
            try
            {
                PersonDAL objdal = new PersonDAL();
                return objdal.Read();
            }
            catch
            {
                throw;
            }
        }
        public DataTable GetPersons(Int16 ID)
        {
            try
            {
                PersonDAL objdal = new PersonDAL();
                return objdal.Read(ID);
            }
            catch
            {
                throw;
            }
        }
       
    }
}

Create Presentation Layer.

This is the top most layer where user will interact with system. We will create simple windows for like below.

Image 1

The form contains one datagrid one textbox and one button. In load event of form we will pull all data and it will show in datagrid. There is another operation, where user can able to fetch particular person by providing person ID. Have a look on below code.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApplication1.BLL;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                PersonBLL p = new PersonBLL();
                this.dataGridView1.DataSource = p.GetPersons(Convert.ToInt16(this.txtID.Text));
            }
            catch
            {
                MessageBox.Show("Error Occurred");
            }
        }
 
        private void Form1_Load(object sender, EventArgs e)
        { 
            try
            {
                PersonBLL p = new PersonBLL();
                this.dataGridView1.DataSource = p.GetPersons();
            }
            catch
            {
                MessageBox.Show("Error Occurred");
            }
        }
    }
}

Folder structure in solution explorer

Here is our sample folder stricture in solution explorer. We have created all layers in same solution. You may create separate solution for each layer.

Image 2

Here is sample output in form load event.

Image 3

If we want to search particular person, we have to provide ID.

Image 4

Table Stricture

Here is our table structure. It contains three fields ID, name and surname.

Table Name:-Person

Image 5

Conclusion

In this article we have discussed how to implement simple 3-tier architecture in C# application. Hope you have understood the concept.

License

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


Written By
Software Developer DELL International
India India
I am software developer from INDIA. Beside my day to day development work, i like to learn new technologies to update myself. I am passionate blogger and author in various technical community including dotnetfunda.com , c-sharpcorner.com and codeproject. My area of interest is modern web technology in Microsoft stack. Visit to my personal blog here.

http://ctrlcvprogrammer.blogspot.in/

Comments and Discussions

 
BugA typos in article Pin
erfan razi19-Dec-16 19:11
erfan razi19-Dec-16 19:11 
Questionit is very helpful Pin
Member 125921534-Jul-16 7:29
Member 125921534-Jul-16 7:29 
SuggestionNice article but this is not about 3-tier - this is about 3-layer architecture Pin
Azamat Kurbanaev14-Mar-16 5:39
Azamat Kurbanaev14-Mar-16 5:39 
PraiseSimple, yet effective explanation Pin
Member 1209034911-Jan-16 5:44
Member 1209034911-Jan-16 5:44 
QuestionTHANKS Pin
Siddaram K.Patil10-Sep-15 1:46
Siddaram K.Patil10-Sep-15 1:46 
QuestionTHANKS FOR A NICE GUIDE Pin
Siddaram K.Patil10-Sep-15 1:46
Siddaram K.Patil10-Sep-15 1:46 
QuestionShould we add layers as new project and class library? PinPopular
Ammar Shaukat23-Jul-15 21:38
professionalAmmar Shaukat23-Jul-15 21:38 
Questioncall connection class in another page Pin
Member 1180004029-Jun-15 1:34
Member 1180004029-Jun-15 1:34 
GeneralMy vote of 5 Pin
Prabin Siwakoti17-Apr-15 0:54
Prabin Siwakoti17-Apr-15 0:54 
QuestionDo we need to Link the Classes? Pin
Dinakar Kulkarni10-Mar-15 4:20
Dinakar Kulkarni10-Mar-15 4:20 
QuestionHow to achieve paging in that gridview. Pin
Chathura Wickramasinghe (ChathurawinD)4-Jan-15 21:57
Chathura Wickramasinghe (ChathurawinD)4-Jan-15 21:57 
General[My vote of 1] Pin
CelPlusPlus11-Sep-14 3:08
CelPlusPlus11-Sep-14 3:08 
Questionis it 3-Tiers or NOT? Pin
Member 1087285816-Jun-14 22:08
Member 1087285816-Jun-14 22:08 
AnswerRe: is it 3-Tiers or NOT? Pin
Member 1054053118-Aug-14 0:32
Member 1054053118-Aug-14 0:32 
GeneralGreat Article Pin
Gurunatha Dogi14-Jun-14 21:13
Gurunatha Dogi14-Jun-14 21:13 
QuestionRegarding 3 tired application Pin
Archana yalagi22-Apr-14 21:44
Archana yalagi22-Apr-14 21:44 
GeneralMy vote of 2 Pin
Shubhada Fuge4-Apr-14 21:34
Shubhada Fuge4-Apr-14 21:34 
Question3-Tier/ Layer Pin
Shubhada Fuge4-Apr-14 21:33
Shubhada Fuge4-Apr-14 21:33 
QuestionThank you. Pin
Kaysikarline14-Jan-14 15:56
Kaysikarline14-Jan-14 15:56 
GeneralThanks... Pin
pirateworks18-Dec-13 11:59
pirateworks18-Dec-13 11:59 
GeneralMy vote of 4 Pin
Marimuthu.K11-Nov-13 22:57
Marimuthu.K11-Nov-13 22:57 
Questiongenerates codes in 3 tier(3layer ) for application and web using c# Pin
Rahim Lotfi9-Nov-13 3:21
Rahim Lotfi9-Nov-13 3:21 
GeneralMy vote of 1 Pin
Akhil Mittal2-Oct-13 22:30
professionalAkhil Mittal2-Oct-13 22:30 
GeneralMy vote of 2 Pin
Klaus Luedenscheidt2-Oct-13 17:48
Klaus Luedenscheidt2-Oct-13 17:48 
GeneralRe: My vote of 2 Pin
Shubhada Fuge4-Apr-14 21:36
Shubhada Fuge4-Apr-14 21:36 

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.