Pass Data in Layered Architecture: Part-1: Uniformly Using Entity Class

This article explains how to pass data across layers in a uniform fashion using an entity class. We know that tiered architecture is a very popular architecture in the software development field. So, we will create a different layer to meet our business needs and to follow the separation of concerns in software development.

The next question is, how will we pass data across layers? The answer is not simple. There are many ways and patterns to follow for this problem. In this article we will see how to pass data across layers uniformly using an entity class.

What is Entity class?

Obviously it is a valid question. Entities are nothing but our business objects. For example we want to save some information of a patient in an EMR application, to do that we can create a patient entity. It's nothing but a normal C# class containing information about a patient and functions to manipulate the patient.

Let's create one simple entity class

We have just not explained that entitles are nothing but classes. Let's create a Person Entity. Have a look at the following code.

public class Person
{
   
public Int16 ID { get; set; }
    
public string name { get; set; }
    
public string surname { get; set; }
}

This is a very simple example of an entity class. It contains three properties called ID, name and surname.

We will now create a simple 3-Tier architecture project and we will transfer an object of the entity class above from one layer to another layer.

Create Data Access Layer

Let's start with the bottom-most layers. We will create a Data Access Layer that will read and insert data in a SQL Server database. Have a look at the following code.

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.SqlClient;

using WindowsFormsApplication1.DTO;

 

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();

        List<Person> List = new List<Person>();

        Person objP = null;

 

 

        public List<Person> Read()

        {

           

            con.ConnectionString = ConString;

            if (ConnectionState.Closed == con.State)

                con.Open();

            SqlCommand cmd = new SqlCommand("select * from Person",con);

            try

            {

                SqlDataReader rd = cmd.ExecuteReader();

                while (rd.Read())

                {

                    objP = new Person();

                    objP.ID = Convert.ToInt16(rd.GetValue(0));

                    objP.name = rd.GetString(1);

                    objP.surname = rd.GetString(2);

                    List.Add(objP);

 

                }

                return List;

            }

            catch

            {

                throw;

            }

        }

 

        public List<Person> 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();

                while (rd.Read())

                {

                    objP = new Person();

                    objP.ID = rd.GetInt16(0);

                    objP.name = rd.GetString(1);

                    objP.surname = rd.GetString(2);

                    List.Add(objP);

                }

                return List;

            }

            catch

            {

                throw;

            }

        }

        public Int32 Insert(Person tmp)

        {

            try

            {

                con.ConnectionString = ConString;

                if (ConnectionState.Closed == con.State)

                    con.Open();

                SqlCommand cmd = new SqlCommand("INSERT INTO Person VALUES (@name,@surname)", con);

                cmd.Parameters.AddWithValue("@name", tmp.name);

                cmd.Parameters.AddWithValue("@surname", tmp.surname);

 

                return cmd.ExecuteNonQuery();

            }

            catch

            {

                throw;

            }

        }

 

 

    }

}

Here we have implemented two overloaded functions to read the data. One will dump all data from the table and another will fetch information of a specific person. The Insert function will insert a single set of information into the database.

Note that the return type of the function or argument of the Insert method is an object of the entity class. Within the read function we are reading data from the database object and transforming it to a business object.

Create Business Logic Layer

We will now create a Business Logic Layer that will communicate with the both User Interface layer (Presentaion Layer) and Data Access Layer. Have a look at the following code.
 

using System;

using System.Collections.Generic;

using System.Data;

using WindowsFormsApplication1.DAL;

using WindowsFormsApplication1.DTO;

 

namespace WindowsFormsApplication1.BLL

{

    public class PersonBLL

    {

        public List<Person> GetPersons()

        {

            try

            {

                PersonDAL objdal = new PersonDAL();

                return objdal.Read();

            }

            catch

            {

                throw;

            }

        }

        public List<Person> GetPersons(Int16 ID)

        {

            try

            {

                PersonDAL objdal = new PersonDAL();

                return objdal.Read(ID);

            }

            catch

            {

                throw;

            }

        }

        public Boolean SavePerson(Person tmp)

        {

            try

            {

                PersonDAL objDal = new PersonDAL();

                return objDal.Insert(tmp) > 0 ? true : false;

            }

            catch

            {

                throw;

            }

        }

      

    }

}


The functions are very simple, the GetPerson() function will return a list of entity objects and the SavePerson() function will transfer an object of the entity class to the Data Access Layer. So, overall all the functions are transferring an object of the entity class across layers.

Create Presentation Layer

This is a high-level layer where the user will provide input to and get output from the system. Create one simple Windows Forms form as in the following.

Write the following code in the button's click event and the form's load event.
 

using System;

using System.Data;

using System.Windows.Forms;

using WindowsFormsApplication1.BLL;

using WindowsFormsApplication1.DTO;

 

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");

            }

        }

 

        private void label1_Click(object sender, EventArgs e)

        {

 

        }

 

        private void button2_Click(object sender, EventArgs e)

        {

            //Save Data

            Person objP = new Person();

            objP.name = this.txtname.Text;

            objP.surname = this.txtsurname.Text;

            PersonBLL objBLL = new PersonBLL();

            try

            {

                if(objBLL.SavePerson(objP))

                {

                    MessageBox.Show("Data Saved successfully");

                    Form1_Load(null, null);

                }

            }

            catch

            {

                MessageBox.Show("Exception occurred");

            }

 

        }

    }

}


In the form's load event data will be returned in the form of a list and we are directly assigning the list to a grid view object. The save function will send data to a business object in the form of an entity.

Here is our project structure:

PassData1.jpg

Here is the output screen, by default the data will be loaded from the database.

PassData2.jpg

Let's try to insert new data.

PassData3.jpg

After the save:

PassData4.jpg

Ok, it has been saved.

Conclusion

In this article we learned how to pass data in a layered architecture in a uniform fashion. Hope you have understood the concept. In a future article we will see a few more ways to pass data in a layered architecture.
 

Up Next
    Ebook Download
    View all
    Learn
    View all