Thursday, 3 August 2017

Insert, Delete, Update Using Entity Framework and LINQ in ASP.NET


1> Create Database First
2> Create Table

3> Add ADO.Net Entity Model in your project


4> Choose EFDesigner 



5> Click on connection and enter server name and choose database and click on OK.



6> Click on next button two times and you will get the properties of your table on the Page like


7> Add connectionstring on the web.config file.

web.config:-

 <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-insertdeleteupdateEFasp-20170801105050.mdf;Initial Catalog=aspnet-insertdeleteupdateEFasp-20170801105050;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="entityframeworkdemosEntities" connectionString="metadata=res://*/studentmodel.csdl|res://*/studentmodel.ssdl|res://*/studentmodel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=*****;initial catalog=entityframeworkdemos;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>


8> Add a form name studentdetails in your project


studentdetails.aspx:-

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="studentdetails.aspx.cs" Inherits="insertdeleteupdateEFasp.studentdetails" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <table>
           <tr>
               <td>
                   Name:
               </td>
               <td>
                   <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
               </td>
           </tr>
           <tr>
               <td>
                   Contact Number:
               </td>
               <td>
                   <asp:TextBox ID="txt_contact" TextMode="Number" runat="server"></asp:TextBox>
               </td>
           </tr>
            <tr>
               <td>
                   Address:
               </td>
               <td>
                   <asp:TextBox ID="txt_add" runat="server"></asp:TextBox>
               </td>
           </tr>

              <tr>
               <td>
                   Class:
               </td>
               <td>
                   <asp:TextBox ID="txt_class" runat="server"></asp:TextBox>
               </td>
           </tr>

                         <tr>
               <td>
                   Email:
               </td>
               <td>
                   <asp:TextBox ID="txt_email" runat="server"></asp:TextBox>
               </td>
           </tr>
              
             
       </table>
        <asp:Button ID="btn_submit" runat="server" Text="submit" OnClick="btn_submit_Click" />
    
    </div>
        

        <div style="margin-top:20px; margin-left:30%;">

            <asp:GridView ID="grvdtudentdetails" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField HeaderText="Id" DataField="id"/>
                    <asp:BoundField HeaderText="Name" DataField="name" />
                    <asp:BoundField HeaderText="Contact Number" DataField="contactnumber" />
                    <asp:BoundField HeaderText="Address" DataField="address" />
                    <asp:BoundField HeaderText="Class" DataField="class" />
                    <asp:BoundField HeaderText="Email" DataField="email" />
                    <asp:TemplateField HeaderText="Update">
                        <ItemTemplate>
                            <asp:Button ID="btn_update" runat="server" Text="Update" OnClick="btn_update_Click" CommandName='<%#Eval("id") %>'/>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Delete">
                        <ItemTemplate>
                            <asp:Button ID="btn_delete" runat="server" Text="Delete" OnClick="btn_delete_Click" CommandName='<%#Eval("id") %>' OnClientClick="return confirm('delete?')" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                
            </asp:GridView>

        </div>
    </form>
</body>
</html>

studentdetails.aspx.cs:-

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

namespace insertdeleteupdateEFasp
{
    public partial class studentdetails : System.Web.UI.Page
    {
        entityframeworkdemosEntities demo = new entityframeworkdemosEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
if(!IsPostBack)
            {
                studentdetailbind();
            }
            
        }
        public void studentdetailbind()
        {
            entityframeworkdemosEntities demo1 = new entityframeworkdemosEntities();
            grvdtudentdetails.DataSource = demo1.studentoperations.ToList();
            grvdtudentdetails.DataBind();
        }

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            entityframeworkdemosEntities demo = new entityframeworkdemosEntities();
            if (Session["id"] == null)
            {
                studentoperation sp = new studentoperation();
                sp.name = txt_name.Text;
                sp.contactnumber = txt_contact.Text;
                sp.address = txt_add.Text;
                sp.@class = txt_class.Text;
                sp.email = txt_email.Text;
                demo.studentoperations.Add(sp);
                demo.SaveChanges();
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "validations", "alert('insert successfully')", true);
                txt_name.Text = ""; txt_contact.Text = ""; txt_add.Text = ""; txt_class.Text = ""; txt_email.Text = "";
            }
            else
            {
                entityframeworkdemosEntities demo1 = new entityframeworkdemosEntities();
                studentoperation sp1 = new studentoperation();
                sp1.id = Convert.ToInt32(Session["id"]);
                sp1.name = txt_name.Text;
                sp1.contactnumber = txt_contact.Text;
                sp1.address = txt_add.Text;
                sp1.@class = txt_class.Text;
                sp1.email = txt_email.Text;
                demo1.Entry(sp1).State = System.Data.Entity.EntityState.Modified;
                demo1.SaveChanges();
                Session["id"] = null;
                txt_name.Text = ""; txt_contact.Text = ""; txt_add.Text = ""; txt_class.Text = ""; txt_email.Text = "";
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "validations", "alert('Update successfully');window.location.href='../../../../studentdetails.aspx;", true);
                //Response.Redirect("~/studentdetails.aspx");
               
            }
        }

        protected void btn_update_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            int id = Convert.ToInt32(btn.CommandName);
            studentoperation sp = demo.studentoperations.Find(id);
            Session["id"] = sp.id;
            txt_name.Text = sp.name;
            txt_contact.Text = sp.contactnumber;
            txt_add.Text = sp.address;
            txt_class.Text = sp.@class;
            txt_email.Text = sp.email;
        }

        protected void btn_delete_Click(object sender, EventArgs e)
        {
            entityframeworkdemosEntities demo1 = new entityframeworkdemosEntities();
            Button btn = sender as Button;
            int id = Convert.ToInt32(btn.CommandName);
            studentoperation sp = demo1.studentoperations.Find(id);
            
            demo1.studentoperations.Remove(sp);
            demo1.SaveChanges();
            Response.Redirect("~/studentdetails.aspx");
        }
    }
}


Your Context class and Models are in the project after adding the ADO.net entity data model.
They will look under the folder like below snapshot:-













Insert, Delete, Update Using Entity Framework and LINQ in ASP.NET 1> Create Database First 2> Create Table 3> Add ADO...