header1.html

Friday, 16 August 2013

CRUD operation using Entity Framework and LINQ



This article is for beginners who are new to EF Terminology and currently working on ADO.NET by creating DAL,BAL to interact with database.
First question comes in to picture is What is Entity Framework?
Lets see the definition given by Microsoft-"The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals."
So,Entity Framework is ORM(Object/Relational Mapping) framework.
ORM helps to keep database design separate from domain Class design and it also improves standard CRUD (Create, Read, Update & Delete)operation.
Entity Framework 4.1 have multiple modeling techniques like code first, model first or database first.Here we are going to implement Database first approach. In this article we are also going to implement LINQ(Language Integrated Query)to perform CRUD operation with entity model.
To implement Database/Model first approach we need to create database first,
Query to create Database in SQL Server:

CREATE DATABASE MYCART

Query To create PRODUCTS table in MYCART Database:

USE MYCART
CREATE TABLE PRODUCTS
(
 Product_ID int IDENTITY(100,1) NOT NULL primary key,
 Product_Name varchar(20),
 Product_Desc varchar(50),
 Product_Price money,
 Quantity int
)

Create New ASP.NET Application:Create application "EF_CRUD" and add AddProduct.aspx page to implement CREATE operation.
structureCareerWebHelper
Sample Structure

Create the First simple Entity Data Model (EDM):
Solution Explorer =>right click on project => Add => New Item. Select the Data Template => ADO.NET Entity Data Model and click Add.
edmx

Rename it as ProductModel.edmx

It opens Entity Data Model Wizard. Select "Generate from database" option and click "Next"

Now enter your credentials and your database details as follows.
CareerWebHelperEM

StepsEF

By double clicking on ProductModel.edmx, it will open EDM designer which displays all the entities for selected tables and relation between them.Now check Entity model will be generated like
ProductModel

CREATE/INSERT Operation:Check AddProduct.aspx.cs ---Download
Create instance of Context MYCARTEntities context = new MYCARTEntities();
protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {

                PRODUCT objProduct = new PRODUCT();
                objProduct.Product_Name = txtName.Text;
                objProduct.Product_Desc = txtPdesc.Text;
                objProduct.Product_Price = decimal.Parse(txtPrice.Text);
                objProduct.Quantity = int.Parse(txtQuantity.Text);

                context.AddToPRODUCTS(objProduct);
                int result=context.SaveChanges();
                if (result != 0)
                {
                    lblMsg.Text = "Product Added!!";  
                }
                else
                {
                    lblMsg.Text = "Failed!!";
                }
                

            }
            catch (Exception ex)
            {

                lblMsg.Text = "Failed!!";
                throw ex;
            }
        }

SaveChanges() method on the context to reflect the changes back to database.This will insert the record into the table.

Now, READ,UPDATE and DELETE OPERATION:1.Add ModifyProduct.aspx page to Project
2.Add GridView to page "gvModifyProducts"
3.Use Template fields and Bound Fields to bind Data to GridView.
4.Create following Method to implement READ Operation
private void BindProductDetails()
        {
            try
            {
                var myData = from c in context.PRODUCTS select new { c.Product_ID, c.Product_Name, c.Product_Desc,       c.Product_Price,c.Quantity };
                gvModifyProducts.DataSource = myData;
                gvModifyProducts.DataBind();
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        
        
        }

5.Now handle Following events
protected void gvModifyProducts_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                gvModifyProducts.EditIndex = e.NewEditIndex;
                BindProductDetails(); 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected void gvModifyProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                BindProductDetails();
                gvModifyProducts.PageIndex = e.NewPageIndex;
                gvModifyProducts.DataBind();
           }
            catch (Exception ex)
            {
                throw ex;
            }
         }

        protected void gvModifyProducts_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
          gvModifyProducts.EditIndex = -1;
            BindProductDetails();

        }
        protected void gvModifyProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                int intID = int.Parse(gvModifyProducts.Rows[e.RowIndex].Cells[0].Text);
                TextBox txtName = (TextBox)gvModifyProducts.Rows[e.RowIndex].Cells[1].FindControl("txtName");
                TextBox txtDesc = (TextBox)gvModifyProducts.Rows[e.RowIndex].Cells[2].FindControl("txtDesc");
                TextBox txtPrice = (TextBox)gvModifyProducts.Rows[e.RowIndex].Cells[3].FindControl("txtPrice");
                TextBox txtQuant = (TextBox)gvModifyProducts.Rows[e.RowIndex].Cells[4].FindControl("txtQuantity");
//This Code is used to handle Validations like Required field
                if (txtName.Text.Trim() == "")
                {
                    txtName.Focus();

                }
               else if (txtDesc.Text.Trim() == "")
                    txtDesc.Focus();
               else if (txtPrice.Text.Trim()=="")txtPrice.Focus();
                else if (txtQuant.Text.Trim()=="")
               txtQuant.Focus();
                else
                {
              var data =
                    (from c in context.PRODUCTS
                     where c.Product_ID == intID
                     select c).First();

                    data.Product_Name = txtName.Text;
                    data.Product_Desc = txtDesc.Text;
                    data.Product_Price = decimal.Parse(txtPrice.Text);
                    data.Quantity = int.Parse(txtQuant.Text);
                    context.SaveChanges();

                    lblMsg.Visible = true;
                    lblMsg.Text = "Product Updated Successfully!!!";
                    BindProductDetails();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected void gvModifyProducts_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int intID = int.Parse(gvModifyProducts.Rows[e.RowIndex].Cells[0].Text);
                PRODUCT p = new PRODUCT();
                p = (from c in context.PRODUCTS
                     where c.Product_ID == intID
                     select c).First();
                context.PRODUCTS.DeleteObject(p);
                
                context.SaveChanges();

                lblMsg.Visible = true;
                lblMsg.Text = "Product  deleted Successfully!!!";
                BindProductDetails();

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

CRUD
READ,UPDATE and DELETE

Hope this article helped you, do write your feedback and comments.
Happy Coding ☺ ☺ ☺
You Can DOWNLOAD Code here
Please write your valuable comments if you liked this.☺

5 comments: