CRUD Operations In Entity Framework

In this article, we will see basic CRUD operation in EF. We have seen articles on EF before. So, before going through this article, I would recommend some basic reads on EF.

What is Entity Framework?

Entity Framework is an ORM framework. ORM stands for Object Relational Mapping.

What is an Object Relational Mapping framework?

Object Relational Mapping framework automatically creates classes, which are based on the database tables and the opposite is also true, i.e., it can also automatically generate necessary SQL to create the database tables, which are based on the classes.

Let’s get started!!

We want to achieve this output


We will create a simple application. First, create a simple empty Web application and give it a suitable name. Now, let’s create a table called "test". Here is the script to create a table. 

  1. USE [TESTING]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[test]    Script Date: 2/9/2017 8:19:29 PM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. CREATE TABLE [dbo].[test](  
  12.     [id] [int] IDENTITY(1,1) NOT NULL,  
  13.     [FirstName] [nvarchar](50) NULL,  
  14.     [MiddleName] [nvarchar](50) NULL,  
  15.     [LastName] [nvarchar](50) NULL,  
  16.     [Address] [nvarchar](50) NULL,  
  17.     [Landmark] [nvarchar](50) NULL,  
  18.     [EmailID] [nvarchar](50) NULL,  
  19. PRIMARY KEY CLUSTERED   
  20. (  
  21.     [id] ASC  
  22. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
  23. ) ON [PRIMARY]  
  24.   
  25. GO   

Adding ADO.NET Entity Data Model file

Now, let's add ADO.NET Entity data model file to our project. Right click on the project ->Add-> ADO.NET Entity Data Models and name it Employee.


Click "OK" and select "EF Designer from database" option.


Click on Next and select the option "include the sensitive data in connection string" and click on "Next". It will ask you which database objects to include in our model . So, select the table which you created.


Click on "Finish" and it will create an Employee.edmx file in our project.


The fields are properly mapped as you can see from the above screenshot with ID as the primary key and the respective fields are associated properly on the designer surface.

GUI Part

Add a webform. Now, let’s setup the GUI part. First, we will include all the support files like bootstrap and jQuery.

  1. <link href="Styles/bootstrap.css" rel="stylesheet" />  
  2.     <script src="Scripts/jquery-1.8.2.js"></script>  
  3.     <script src="Scripts/bootstrap.js"></script>    

These are supporting files for our application; i.e., bootstrap and jQuery. We will be including a modal popup here so first, drag and drop the script manager control on the form

  1. <asp:ScriptManager runat="server" ID="ScriptManager1" />   

Select Code

Now, let’s place the Grid View inside the update panel control.

  1. <!-- Placing GridView in UpdatePanel-->  
  2.             <asp:UpdatePanel ID="upCrudGrid" runat="server">  
  3.                 <ContentTemplate>  
  4.                             
  5.                     <asp:GridView ID="GridView1" runat="server" Width="940px" HorizontalAlign="Center"  
  6.                         OnRowCommand="GridView1_RowCommand" OnPageIndexChanging="GridView1_OnPageIndexChanging"  AutoGenerateColumns="false" AllowPaging="true"  
  7.                         CssClass="table table-hover table-striped" PageIndex="3" PageSize="3">  
  8.                         <Columns>  
  9.                             
  10.                               
  11.                     <asp:BoundField DataField="id" HeaderText="ID"/>  
  12.                             <asp:BoundField DataField="FirstName" HeaderText="FirstName"/>  
  13.                                   <asp:BoundField DataField="MiddleName" HeaderText="MiddleName"/>  
  14.                             <asp:BoundField DataField="LastName" HeaderText="LastName"/>  
  15.                             <asp:BoundField DataField="Address" HeaderText="Address"/>  
  16.                             <asp:BoundField DataField="Landmark" HeaderText="Landmark"/>  
  17.                             <asp:BoundField DataField="EmailID" HeaderText="Email"/>  
  18.                             
  19.   
  20.                           
  21.                                       
  22.                          <asp:ButtonField CommandName="editRecord"    ControlStyle-CssClass="btn btn-info"  
  23.                                 ButtonType="Button" Text="Edit" HeaderText="Edit Record" >  
  24.                                 <ControlStyle CssClass="btn btn-primary" ></ControlStyle>  
  25.                             </asp:ButtonField>  
  26.                             <asp:ButtonField CommandName="deleteRecord" ControlStyle-CssClass="btn btn-info"  
  27.                                 ButtonType="Button" Text="Delete" HeaderText="Delete Record">  
  28.                                 <ControlStyle CssClass="btn btn-danger"></ControlStyle>  
  29.                             </asp:ButtonField>  
  30.                         </Columns>  
  31.                     </asp:GridView>  
  32.                     <asp:Button ID="btnAdd" runat="server" Text="Add New Record" CssClass="btn btn-info" OnClick="btnAdd_Click" />  
  33.                 </ContentTemplate>  
  34.                 <Triggers>  
  35.                 </Triggers>  
  36.             </asp:UpdatePanel>   

Here, in the code, we are selecting records from our database and buttons for editing and deleting and at the bottom we are adding a button for adding a new record.

After setting up the GUI for select, let’s create a simple method for select using EF. 

  1. private void BindGrid()  
  2.         {  
  3.             using (TESTINGEntities test = new TESTINGEntities())  
  4.             {  
  5.                 if (test.tests.Count() > 0)  
  6.                 {  
  7.                     GridView1.DataSource = (from em in test.tests  
  8.                                             select new {em.id, em.FirstName, em.MiddleName, em.LastName, em.Address, em.Landmark, em.EmailID }).ToList();  
  9.                     GridView1.DataBind();  
  10.                 }  
  11.   
  12.                 else  
  13.                 {  
  14.                     GridView1.DataSource = null;  
  15.                     GridView1.DataBind();  
  16.   
  17.                 }  
  18.   
  19.             }  
  20.         }   

And on Page Load let’s call that method BindGrid() as 

  1. protected void Page_Load(object sender, EventArgs e)  
  2.         {  
  3.             if (!IsPostBack)  
  4.             {  
  5.                 BindGrid();  
  6.             }  
  7.         }   

So, it’s a simple straightforward code. Now let’s run the application and check the output

Output for Select

Insert Code

Now let’s setup the GUI part for inserting 

  1. <!-- Add Record Modal Starts here-->  
  2.             <div id="addModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">  
  3.                 <div class="modal-header">  
  4.                     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>  
  5.                     <h3 id="addModalLabel">Add New Record</h3>  
  6.                 </div>  
  7.                 <asp:UpdatePanel ID="upAdd" runat="server">  
  8.                     <ContentTemplate>  
  9.                         <div class="modal-body">  
  10.                             <table class="table table-bordered table-hover">  
  11.   
  12.                             
  13.                                   <tr>  
  14.                                     <td>FirstName : </td>  
  15.                                     <td>  
  16.                                         <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td>  
  17.                                 </tr>  
  18.                                 <tr>  
  19.                                     <td>MiddleName :</td>  
  20.                                     <td>  
  21.                                         <asp:TextBox ID="txtMiddleName" runat="server"></asp:TextBox></td>  
  22.                                 </tr>  
  23.                                 <tr>  
  24.                                     <td>LastName:</td>  
  25.                                     <td>  
  26.                                         <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>  
  27.                                 </tr>  
  28.                                 <tr>  
  29.                                     <td>Address:</td>  
  30.                                     <td>  
  31.                                         <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>  
  32.                                 </tr>  
  33.                                      <tr>  
  34.                                     <td>Landmark:</td>  
  35.                                     <td>  
  36.                                         <asp:TextBox ID="txtLandmark" runat="server"></asp:TextBox></td>  
  37.                                 </tr>  
  38.                                      <tr>  
  39.                                     <td>EmailID:</td>  
  40.                                     <td>  
  41.                                         <asp:TextBox ID="txtEmailID" runat="server"></asp:TextBox></td>  
  42.                                 </tr>  
  43.                                
  44.                             
  45.                               
  46.                                
  47.                             </table>  
  48.                         </div>  
  49.                         <div class="modal-footer">                            
  50.                             <asp:Button ID="btnAddRecord" runat="server" Text="Add" CssClass="btn btn-primary" OnClick="btnAddRecord_Click" />  
  51.                             <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>  
  52.                         </div>  
  53.                     </ContentTemplate>  
  54.                     <Triggers>  
  55.                         <asp:AsyncPostBackTrigger ControlID="btnAddRecord" EventName="Click" />  
  56.                     </Triggers>  
  57.                 </asp:UpdatePanel>  
  58.             </div>  
  59.             <!--Add Record Modal Ends here-->   

Here we had placed the respective textboxes on the modal popup and calling the modal popup on button click in code behind.

We will see how to popup the modal through code behind

 

  1. protected void btnAdd_Click(object sender, EventArgs e)  
  2.         {  
  3.   
  4.             System.Text.StringBuilder sb = new System.Text.StringBuilder();  
  5.             sb.Append(@"<script type='text/javascript'>");  
  6.             sb.Append("$('#addModal').modal('show');");  
  7.             sb.Append(@"</script>");  
  8.             ScriptManager.RegisterClientScriptBlock(thisthis.GetType(), "AddShowModalScript", sb.ToString(), false);  
  9.         }   

So, we created the modal pop up successfully. Now let’s write code for inserting

  1. protected void btnAddRecord_Click(object sender, EventArgs e)  
  2.         {  
  3.   
  4.             using (TESTINGEntities test = new TESTINGEntities())  
  5.             {  
  6.                 test testing = new test();  
  7.                 testing.FirstName = txtFirstName.Text;  
  8.                 testing.MiddleName = txtMiddleName.Text;  
  9.                 testing.LastName = txtLastName.Text;  
  10.                 testing.Address = txtAddress.Text;  
  11.                 testing.Landmark = txtLandmark.Text;  
  12.                 testing.EmailID = txtEmailID.Text;  
  13.                 test.tests.Add(testing);  
  14.                 test.SaveChanges();  
  15.                 System.Text.StringBuilder sb = new System.Text.StringBuilder();  
  16.                 sb.Append(@"<script type='text/javascript'>");  
  17.                 sb.Append("alert('Record Added Successfully');");  
  18.                 sb.Append("$('#addModal').modal('hide');");  
  19.                 sb.Append(@"</script>");  
  20.                 ScriptManager.RegisterClientScriptBlock(thisthis.GetType(), "AddHideModalScript", sb.ToString(), false);  
  21.                 BindGrid();  
  22.   
  23.   
  24.             }  
  25.         }   

So, we are wrapping testingentites inside a using block just to make sure we are properly opening and closing connections properly.We had created a variable called as test and passing those single fields in our test table which is defined in our testentities.

In LINQ to SQL we were having submitchanges() in order to save the form entries.To find out refer LINQ to SQL CRUD operations here,

Here in EF we have savechanges() to save the form fields. And a popup to show that records are inserted successfully.

Performing Edit

On button click (Edit) we want to load all the details of that employee


Let’s setup the GUI part for editing, 

  1. <!-- Edit Modal Starts here -->  
  2.             <div id="editModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">  
  3.                 <div class="modal-header">  
  4.                     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>  
  5.                     <h3 id="editModalLabel">Edit Record</h3>  
  6.                 </div>  
  7.                 <asp:UpdatePanel ID="upEdit" runat="server">  
  8.                     <ContentTemplate>  
  9.                         <div class="modal-body">  
  10.                             <table class="table">  
  11.                               <tr>  
  12.                                    <td>  
  13.                                        ID:  
  14.                                    </td>  
  15.                                    <td>  
  16.                                        <asp:Label ID="lblID" runat="server"></asp:Label>  
  17.                                    </td>  
  18.                                </tr>  
  19.                             
  20.                                 <tr>  
  21.                                     <td>FirstName : </td>  
  22.                                     <td>  
  23.                                         <asp:TextBox ID="txtFirstNameEdit" runat="server"></asp:TextBox></td>  
  24.                                 </tr>  
  25.                                 <tr>  
  26.                                     <td>MiddleName :</td>  
  27.                                     <td>  
  28.                                         <asp:TextBox ID="txtMiddleNameEdit" runat="server"></asp:TextBox></td>  
  29.                                 </tr>  
  30.                                 <tr>  
  31.                                     <td>LastName:</td>  
  32.                                     <td>  
  33.                                         <asp:TextBox ID="txtLastNameEdit" runat="server"></asp:TextBox></td>  
  34.                                 </tr>  
  35.                                 <tr>  
  36.                                     <td>Address:</td>  
  37.                                     <td>  
  38.                                         <asp:TextBox ID="txtAddressEdit" runat="server"></asp:TextBox></td>  
  39.                                 </tr>  
  40.                                      <tr>  
  41.                                     <td>Landmark:</td>  
  42.                                     <td>  
  43.                                         <asp:TextBox ID="txtLandmarkEdit" runat="server"></asp:TextBox></td>  
  44.                                 </tr>  
  45.                                      <tr>  
  46.                                     <td>EmailID:</td>  
  47.                                     <td>  
  48.                                         <asp:TextBox ID="txtEmailIDEdit" runat="server"></asp:TextBox></td>  
  49.                                 </tr>  
  50.                                        
  51.                             </table>  
  52.                         </div>  
  53.                         <div class="modal-footer">  
  54.                             <asp:Label ID="lblResult" Visible="false" runat="server"></asp:Label>  
  55.                             <asp:Button ID="btnSave" runat="server" Text="Update" CssClass="btn btn-info" OnClick="btnSave_Click" />  
  56.                             <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>  
  57.                         </div>  
  58.                     </ContentTemplate>  
  59.                     <Triggers>  
  60.                         <asp:AsyncPostBackTrigger ControlID="GridView1" EventName="RowCommand" />  
  61.                         <asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />  
  62.                     </Triggers>  
  63.                 </asp:UpdatePanel>  
  64.             </div>  
  65.             <!-- Edit Modal Ends here -->   

Let’s write Code for Editing, 

  1. protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)  
  2.         {  
  3.             if (e.CommandName == "editRecord")  
  4.             {  
  5.   
  6.                 int index = Convert.ToInt32(e.CommandArgument);  
  7.   
  8.                 GridViewRow gr = GridView1.Rows[index];  
  9.                 lblID.Text = gr.Cells[0].Text;  
  10.   
  11.                 txtFirstNameEdit.Text = gr.Cells[1].Text;  
  12.                 txtMiddleNameEdit.Text = gr.Cells[2].Text;  
  13.                 txtLastNameEdit.Text = gr.Cells[3].Text;  
  14.                 txtAddressEdit.Text = gr.Cells[4].Text;  
  15.                 txtLandmarkEdit.Text = gr.Cells[5].Text;  
  16.                 txtEmailIDEdit.Text = gr.Cells[6].Text;  
  17.                 ViewState["id"] = lblID.Text;  
  18.                 System.Text.StringBuilder sb = new System.Text.StringBuilder();  
  19.                 sb.Append(@"<script type='text/javascript'>");  
  20.                 sb.Append("$('#editModal').modal('show');");  
  21.                 sb.Append(@"</script>");  
  22.                 ScriptManager.RegisterClientScriptBlock(thisthis.GetType(), "EditModalScript", sb.ToString(), false);  
  23.             }   

We are calling the command button for editing and here we are retrieving values from databases and allocating respective cells. Now we will write code for updating respective values,

  1. protected void btnSave_Click(object sender, EventArgs e)  
  2.         {  
  3.             using (TESTINGEntities test = new TESTINGEntities())  
  4.             {  
  5.                 int id = Convert.ToInt32(ViewState["id"].ToString());  
  6.                   var reg = test.tests.Single(employee => employee.id == id);  
  7.                  
  8.                 reg.FirstName = txtFirstNameEdit.Text;  
  9.                 reg.MiddleName = txtMiddleNameEdit.Text;  
  10.                 reg.LastName = txtLastNameEdit.Text;  
  11.                 reg.Address = txtAddressEdit.Text;  
  12.                 reg.Landmark = txtLandmarkEdit.Text;  
  13.                 reg.EmailID = txtEmailIDEdit.Text;  
  14.                 test.SaveChanges();  
  15.                 System.Text.StringBuilder sb = new System.Text.StringBuilder();  
  16.                 sb.Append(@"<script type='text/javascript'>");  
  17.                 sb.Append("alert('Records Updated Successfully');");  
  18.                 sb.Append("$('#editModal').modal('hide');");  
  19.                 sb.Append(@"</script>");  
  20.                 ScriptManager.RegisterClientScriptBlock(thisthis.GetType(), "EditHideModalScript", sb.ToString(), false);  
  21.             }  
  22.             
  23.             BindGrid();  
  24.   
  25.         }   

So, we are wrapping testentities class inside using block just to make sure we are opening and closing our connection respectively. After that we had created a variable reg and passing single records in our registration table which are defined in our testentities class this will pass the values which are filled with properties i.e. textboxes here. Last, we are calling savechanges() in order to submit those details in our database.

Delete Code

GUI Part 

  1. <!-- Delete Record Modal Starts here-->  
  2.             <div id="deleteModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="delModalLabel" aria-hidden="true">  
  3.                 <div class="modal-header">  
  4.                     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>  
  5.                     <h3 id="delModalLabel">Delete Record</h3>  
  6.                 </div>  
  7.                 <asp:UpdatePanel ID="upDel" runat="server">  
  8.                     <ContentTemplate>  
  9.                         <div class="modal-body">  
  10.                             Are you sure you want to delete the record?  
  11.                            <%-- <asp:HiddenField ID="hfCode" runat="server" />--%>  
  12.                         </div>  
  13.                         <div class="modal-footer">  
  14.                             <asp:Button ID="btnDelete" runat="server" Text="Delete" CssClass="btn btn-info" OnClick="btnDelete_Click" />  
  15.                             <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Cancel</button>  
  16.                         </div>  
  17.                     </ContentTemplate>  
  18.                     <Triggers>  
  19.                         <asp:AsyncPostBackTrigger ControlID="btnDelete" EventName="Click" />  
  20.                     </Triggers>  
  21.                 </asp:UpdatePanel>  
  22.             </div>  
  23.             <!--Delete Record Modal Ends here -->   

Code for Delete operation 

  1. else if (e.CommandName == "deleteRecord")  
  2.             {  
  3.   
  4.                 int emp_ID = Convert.ToInt32(e.CommandArgument);  
  5.                 TESTINGEntities empDB = new TESTINGEntities();  
  6.                 var emp = empDB.tests.Single(employee => employee.id == emp_ID);  
  7.                 empDB.tests.Remove(emp);  
  8.                 empDB.SaveChanges();  
  9.                 BindGrid();  
  10.             }   

This is simple straight forward code of Delete button. We are first capturing the ID of employee and then we have created the test entities object of our sample class. We are calling save changes  and deleting ID. Simple and straight forward code again.

Code for Edit and Delete

  1. protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)  
  2.         {  
  3.             if (e.CommandName == "editRecord")  
  4.             {  
  5.   
  6.                 int index = Convert.ToInt32(e.CommandArgument);  
  7.   
  8.                 GridViewRow gr = GridView1.Rows[index];  
  9.                 lblID.Text = gr.Cells[0].Text;  
  10.   
  11.                 txtFirstNameEdit.Text = gr.Cells[1].Text;  
  12.                 txtMiddleNameEdit.Text = gr.Cells[2].Text;  
  13.                 txtLastNameEdit.Text = gr.Cells[3].Text;  
  14.                 txtAddressEdit.Text = gr.Cells[4].Text;  
  15.                 txtLandmarkEdit.Text = gr.Cells[5].Text;  
  16.                 txtEmailIDEdit.Text = gr.Cells[6].Text;  
  17.                 ViewState["id"] = lblID.Text;  
  18.                 System.Text.StringBuilder sb = new System.Text.StringBuilder();  
  19.                 sb.Append(@"<script type='text/javascript'>");  
  20.                 sb.Append("$('#editModal').modal('show');");  
  21.                 sb.Append(@"</script>");  
  22.                 ScriptManager.RegisterClientScriptBlock(thisthis.GetType(), "EditModalScript", sb.ToString(), false);  
  23.             }  
  24.   
  25.             else if (e.CommandName == "deleteRecord")  
  26.             {  
  27.   
  28.                 int emp_ID = Convert.ToInt32(e.CommandArgument);  
  29.                 TESTINGEntities empDB = new TESTINGEntities();  
  30.                 var emp = empDB.tests.Single(employee => employee.id == emp_ID);  
  31.                 empDB.tests.Remove(emp);  
  32.                 empDB.SaveChanges();  
  33.                 BindGrid();  
  34.             }  
  35.   
  36.         }  

So, we are done now. Now, run the application and perform CRUD operation in EF.


Similar Articles