Entity Classes and Entity Objects in C#

 

Generally we use the DataSet or DataTable to store the data or to pass the data between UI layer and DB layer. But DataSet or DataTable is heavy object and it takes a lot of memory in the system that will increase the performance of the application. In this type of situation use entity classes to store data or to pass between layers.

Entity class is nothing but normal public class which has several properties to save the individual fields. As shown below we have Product entity class which has three public properties to store product Id, Product Name and Product price.

 

using System;

///<summary>

/// this is the entity class to store theproduct information

///</summary>

public class Product

{

                public Product()

                {

                                //

                                // TODO: Add constructor logic here

                                //

                }

 

    public int Id { get; set; }

 

    public string Name { get; set; }

 

    public double Price { get; set; }

}

 

To store the data and to pass between layers by using Product entity class, create object for Product class and assign each field to the specific property as shown below.

using System;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

 

    protected void btn_Click(object sender, EventArgs e)

    {

        SaveData();

    }

 

    private void SaveData()

    {

        try

        {

            Product objProduct = new Product();

            objProduct.Id = Convert.ToInt32(txtId.Text);

            objProduct.Name = txtName.Text;

            objProduct.Price = Convert.ToDouble(txtPrice.Text);

 

            SaveDataInDB(objProduct);

        }

        catch (Exception ex)

        { }

    }

 

    private void SaveDataInDB(Product obj)

    {

        //call Database to save data

    }

}

 

Now you can pass the Product entity class object objProduct between layers to save the data in DB. You can get the information back from object as shown below.

private void GetProductData(Product objProduct)

{

        txtId.Text = objProduct.Id.ToString();

        txtName.Text = objProduct.Name;

        txtPrice.Text = objProduct.Price.ToString();

}


You can download the source code by clicking below.

                                                                                       CSharpEntityClasses.zip (3.61 kb)