How to do insert/Update/Delete using Entity Framework in asp.net ? Part #3


Hi
I hope that you are knowing the database mapping concept of EF. If not then please see my previous post How to fill gridview using EF?

For doing CRUD operation using EF, we have to do like this
srep1: Take gridview,Lable,Hidden field asp.net control and design the page like above

<div>

<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" AllowPaging="true"
CellPadding="4" ForeColor="#333333" GridLines="None" Width="417px"
onpageindexchanging="Gridview1_PageIndexChanging"
onrowcommand="Gridview1_RowCommand"
onrowdeleting="Gridview1_RowDeleting" onrowediting="Gridview1_RowEditing">
<RowStyle BackColor="#E3EAEB" />
<Columns>
<asp:TemplateField HeaderText="SI.No">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="EmpName" DataField="EmpName" />
<asp:BoundField HeaderText="EmpSal" DataField="EmpSal" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CausesValidation="false" CommandName="Edit" CommandArgument='<%# Eval("Id") %>’ OnClientClick="return confirm(‘Are you sure?’)" />
<asp:LinkButton ID="LinkDelete" runat="server" Text="Delete" CausesValidation="false" CommandName="Delete" CommandArgument='<%# Eval("Id") %>’ OnClientClick="return confirm(‘Are you sure?’)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />

</asp:GridView>
<asp:HiddenField ID="HiddenField1" runat="server" />

</div>

Step2: Write the code in code behind page like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
fillGrid();
}

//This code is used for fetch data from database
protected void fillGrid()
{
using (TestModel.TestEntities TE = new TestModel.TestEntities())
{
var query = from m in TE.tblEmp
orderby m.Id descending
select m;
Gridview1.DataSource = query;
Gridview1.DataBind();
}
}

protected void BtnSubmit_Click(object sender, EventArgs e)
{
if (BtnSubmit.Text == "Submit")
{
SaveEmpData();

fillGrid();
}
else if (BtnSubmit.Text == "Update")
{
UpdateEmpRecord();
fillGrid();

}

}

//This code is used for Update functionality
private void UpdateEmpRecord()
{
using (TestModel.TestEntities TE = new TestModel.TestEntities())
{
int Id1=Convert.ToInt32(HiddenField1.Value);
var query = (from m in TE.tblEmp
where m.Id==Id1
select m).First();

query.EmpName = txtEmpName.Text;
query.EmpSal = txtEmpSal.Text;
TE.SaveChanges();
lblmsg.Text = "Data has been updated Sucessfully";
BtnSubmit.Text = "Submit";
txtEmpName.Text = "";
txtEmpSal.Text = "";
}

}

// This code is used for save functionality
private void SaveEmpData()
{
using (TestModel.TestEntities TE = new TestModel.TestEntities())
{

TestModel.tblEmp objEmp = new TestModel.tblEmp();
objEmp.EmpName = txtEmpName.Text;
objEmp.EmpSal = txtEmpSal.Text;
TE.AddTotblEmp(objEmp);
TE.SaveChanges();
lblmsg.Text = "Data has been inserted sucessfully";
txtEmpName.Text = "";
txtEmpSal.Text = "";
}

}

protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
// This code is used for Delete functionality

if (e.CommandName == "Delete")
{
using(TestModel.TestEntities TE=new TestModel.TestEntities())
{
int id1 = Convert.ToInt32(e.CommandArgument);
var user = TE.tblEmp.First(m => m.Id == id1);
TE.DeleteObject(user);
TE.SaveChanges();
fillGrid();
lblmsg.Text = "";
txtEmpName.Text = "";
txtEmpSal.Text = "";

}

}

//This code is used for fetching particular row of gridview and dispaly on
// respective textbox field

else if (e.CommandName == "Edit")
{
using (TestModel.TestEntities TE = new TestModel.TestEntities())
{
int id1 = Convert.ToInt32(e.CommandArgument);
var Empinfo = GetEmpInfo(id1);
txtEmpName.Text= Empinfo[0].EmpName.ToString();
txtEmpSal.Text = Empinfo[0].EmpSal.ToString();
HiddenField1.Value= Empinfo[0].Id.ToString();
BtnSubmit.Text = "Update";
}
}

}
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

}
protected void Gridview1_RowEditing(object sender, GridViewEditEventArgs e)
{

}
//This code is used for paging
protected void Gridview1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Gridview1.PageIndex = e.NewPageIndex;
fillGrid();

}

private List<TestModel.tblEmp> GetEmpInfo(int Id)
{
using (TestModel.TestEntities TE = new TestModel.TestEntities())
{
return (from m in TE.tblEmp
where m.Id == Id
select m).ToList();
}
}

}

Advertisements

5 Responses to “How to do insert/Update/Delete using Entity Framework in asp.net ? Part #3”

  1. Richard Says:

    I guess what I fail to understand is what is so great about the EF. To me it looks like it does the same thing. I used Linq with the EF and found it no different then creating stored procs to do my business. I guess I am not catching what the big deal is? Thanks for the posts I read them all!!

  2. Chandra Dev Says:

    Hi friend

    did you read this post ? i have included in my first post
    http://blogs.msdn.com/b/dsimmons/archive/2008/05/17/why-use-the-entity-framework.aspx?PageIndex=2#comments

    he had explained very well the difference between ado.net,LINQ to SQL and EF

  3. Umesh Says:

    nice blog……..

    • Chandra Dev Says:

      Thanks

  4. [RESOLVED]How to convert UPDATE from SQL to LINQ in Entittyframework? | ASP Web Form Data Control Says:

    […]  https://chandradev819.wordpress.com/2011/05/13/how-to-do-insertupdatedelete-using-entity-framework-in&#8230; […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: