c-sharp
  1. c-sharp-3-tier-architecture-in-c

C# 3-Tier Architecture in C#

In C#, the 3-tier architecture is a software design pattern that separates the application's functionality into three layers: presentation layer, business layer, and data access layer. This design pattern provides modularity, flexibility, and scalability to the application. In this tutorial, we'll discuss the 3-tier architecture in C# and provide an example.

Syntax

There is no specific syntax for implementing the 3-tier architecture in C#. It is a design pattern that can be implemented in various ways depending on the specific application requirements.

Example

Let's say we want to create an application that allows users to view, add, and delete customer data. Here's how we can implement the 3-tier architecture in our application:

Presentation Layer

The presentation layer is responsible for displaying the user interface and receiving user input. In our application, we'll create a Windows Forms application that displays a list of customers and allows the user to add and delete customers.

public partial class Form1 : Form {
    private BusinessLayer _bl = new BusinessLayer();

    public Form1() {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e) {
        RefreshGrid();
    }

    private void RefreshGrid() {
        dataGridView1.DataSource = _bl.GetAllCustomers();
    }

    private void btnAdd_Click(object sender, EventArgs e) {
        _bl.AddCustomer(txtName.Text);
        RefreshGrid();
    }

    private void btnDelete_Click(object sender, EventArgs e) {
        _bl.DeleteCustomer((int)dataGridView1.CurrentRow.Cells["Id"].Value);
        RefreshGrid();
    }
}

Business Layer

The business layer is responsible for implementing the application's logic. It receives requests from the presentation layer, processes the requests, and returns the results. In our application, we'll create a BusinessLayer class that handles customer data.

public class BusinessLayer {
    private DataAccessLayer _dal = new DataAccessLayer();

    public List<Customer> GetAllCustomers() {
        return _dal.GetAllCustomers();
    }

    public void AddCustomer(string name) {
        _dal.AddCustomer(new Customer { Name = name });
    }

    public void DeleteCustomer(int id) {
        _dal.DeleteCustomer(id);
    }
}

Data Access Layer

The data access layer is responsible for communicating with the database. It receives requests from the business layer, executes the requests, and returns the results. In our application, we'll create a DataAccessLayer class that interacts with a SQL Server database.

public class DataAccessLayer {
    private string _connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

    public List<Customer> GetAllCustomers() {
        List<Customer> customers = new List<Customer>();
        using (SqlConnection conn = new SqlConnection(_connStr)) {
            conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn);
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read()) {
                Customer customer = new Customer {
                    Id = rdr.GetInt32(rdr.GetOrdinal("Id")),
                    Name = rdr.GetString(rdr.GetOrdinal("Name"))
                };
                customers.Add(customer);
            }
            rdr.Close();
        }
        return customers;
    }

    public void AddCustomer(Customer customer) {
        using (SqlConnection conn = new SqlConnection(_connStr)) {
            conn.Open();
            SqlCommand cmd = new SqlCommand("INSERT INTO Customers (Name) VALUES (@Name)", conn);
            cmd.Parameters.AddWithValue("@Name", customer.Name);
            cmd.ExecuteNonQuery();
        }
    }

    public void DeleteCustomer(int id) {
        using (SqlConnection conn = new SqlConnection(_connStr)) {
            conn.Open();
            SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE Id=@Id", conn);
            cmd.Parameters.AddWithValue("@Id", id);
            cmd.ExecuteNonQuery();
        }
    }
}

Output

When we run the example code above, we'll get a Windows Forms application that displays a list of customers and allows us to add and delete customers from a SQL Server database.

Explanation

In the example above, we implemented the 3-tier architecture in a C# application that allows users to view, add, and delete customer data. We divided the application's functionality into three layers: presentation layer, business layer, and data access layer.

  • The presentation layer is responsible for displaying the user interface and receiving user input. We created a Windows Forms application that displays a list of customers and allows the user to add and delete customers.
  • The business layer is responsible for implementing the application's logic. We created a BusinessLayer class that handles customer data and communicates with the data access layer.
  • The data access layer is responsible for communicating with the database. We created a DataAccessLayer class that interacts with a SQL Server database and retrieves, adds, and deletes customer data.

Use

The 3-tier architecture in C# is useful for creating modular, flexible, and scalable applications. It allows developers to separate the application's functionality into three layers, providing clear division of responsibility and easier maintenance. It is especially useful for large-scale applications where functionality needs to be clearly separated and organized.

Important Points

  • The 3-tier architecture in C# is a design pattern that separates the application's functionality into three layers: presentation layer, business layer, and data access layer.
  • The presentation layer is responsible for displaying the user interface and receiving user input.
  • The business layer is responsible for implementing the application's logic.
  • The data access layer is responsible for communicating with the database.

Summary

In this tutorial, we discussed the 3-tier architecture in C# and provided an example of how to implement it in a Windows Forms application that displays and adds customer data to a SQL Server database. We covered the syntax, example, output, explanation, use, and important points of the 3-tier architecture in C#. With this knowledge, you can create modular, flexible, and scalable applications using the 3-tier architecture design pattern.

Published on: