Entity Framework - Basic Guide To Perform Fetch, Filter, Insert, Update And Delete

Previously, I wrote an article regarding how to perform basic database operations using LINQ to SQL here: Basic Guide To Perform Fetch, Filter, Insert, Update And Delete.

In this article, we’re going to see the basics on how to work with data using MS Entity Framework with practical examples in ASP.NET Web Forms. If you are looking for examples in ASP.NET MVC, then head over to my series of articles about: Building Web Application Using Entity Framework And MVC 5.

Or download my eBook here: ASP.NET MVC 5: A Beginner’s Guide

As an overview, ADO.NET Entity Framework (EF) is an object-relational mapping (ORM) framework for the .NET Framework. EF enables developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. The goal is to decrease the amount of code and maintenance required for data-oriented applications. Entity Framework applications provide the following benefits:

  • Applications can work in terms of a more application-centric conceptual model, including types with inheritance, complex members, and relationships.
  • Applications are freed from hard-coded dependencies on a particular data engine or storage schema.
  • Mappings between the conceptual model and the storage-specific schema can change without changing the application code.
  • Developers can work with a consistent application object model that can be mapped to various storage schemas, possibly implemented in different database management systems.
  • Multiple conceptual models can be mapped to a single storage schema.
  • Language-integrated query (LINQ) support provides compile-time syntax validation for queries against a conceptual model.

For details about ADO.NET Entity Framework, see: The ADO.NET Entity Framework Overview

Let’s Get Started!

Now, let’s go ahead and fire up Visual Studio and then select File -> New Project -> Visual C# -> Web - ASP.NET Web Application. Enter the name of the application as you would please, and then click OK to generate the default files.

Adding the .EDMX File

Now, add a new folder under the root of the application and name it as "Model". Within that folder add another folder and name it as "DB". The application structure should now look something like the below:

db

After that, right click on the "DB" folder and select Add -> New Item -> Data -> ADO.NET Entity Data Model just like in the figure below,

New Item

Notice that I have named the entity as "SampleModel" just for the purpose of this demo. You may want to name it to a more appropriate name based on your requirement, but for this example, let's just use "SampleModel". Now, click Add to continue and on the next step select "Generate from database" and click Next. On the next step you can connect or browse to the database that you want to use in the application and test the connection string by clicking on the "Test Connection" button. If it succeeds, then you can continue by clicking OK and then Next.

Note that in this example, I created a simple database called "DeveloperReport.mdf" and added it into the application's App_Data folder. We will be using the aforementioned database for this entire article.

Here’s the screenshot after browsing the database,

database

On the next step, we can add the table(s), views or stored procedures that we want to use in the application by selecting the checkbox, just like in the figure shown below,

checkbox

Notice that we’ve only selected the "SysUser" table. This is because we are going to use this table for doing insert and we don't need anything else. Now click on the Finish button to generate the following entity model below:

model

What happened there is that EF will automatically generate the business object (classes) for us within the Entity Data Model (EDM) that we have just created earlier, and let you query against it. The EDM is the main gateway by which you retrieve objects from the database and resubmit changes. If you’re still confused, don’t worry as we will be seeing how it actually works soon enough.

Setting Up the Form

At this point, we already have our model in place. Now, it’s time for us to set up our GUI. Let's add a new WebForm page. To do this, just right click on the project and select Add -> New Item -> Web -> Webform using Master Page, and then click Add. For the simplicity of this demo, we’ll just set up the GUI like this:

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebAppDemo.WebForm1" %>  
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">  
  3. </asp:Content>  
  4. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">  
  5.     <h1>Add New</h1>  
  6.     <table>  
  7.         <tr>  
  8.             <td>First Name</td>  
  9.             <td><asp:TextBox ID="tbFirstName" runat="server" /></td>  
  10.         </tr>  
  11.         <tr>  
  12.             <td>Last Name</td>  
  13.             <td><asp:TextBox ID="tbLastName" runat="server" /></td>  
  14.         </tr>  
  15.         <tr>  
  16.             <td>Contact Number</td>  
  17.             <td><asp:TextBox ID="tbContactNumber" runat="server" /></td>  
  18.         </tr>  
  19.         <tr>  
  20.             <td>Login ID</td>  
  21.             <td><asp:TextBox ID="tbLoginID" runat="server" /></td>  
  22.         </tr>  
  23.         <tr>  
  24.             <td>Password</td>  
  25.             <td><asp:TextBox ID="tbPassword" runat="server" TextMode="Password" /></td>  
  26.         </tr>  
  27.     </table>  
  28.     <br />  
  29.     <asp:Label ID="lblMessage" runat="server" />  
  30.     <br />  
  31.     <asp:Button ID="btnAdd" runat="server" Text="Add" />  
  32. </asp:Content>  
Nothing fancy there. The markup above just contains some basic server controls to compose the page.

Creating the Object Manager Class

The next step that we are going to do is to create an object manager class that handles the CRUD operations. The purpose of this class is to separate the actual data operations from our code behind, and to have a central class for handling Insert, Update, Fetch and Delete operations.

Now, right click on the "Model" folder and add a new class by selecting Add -> Class. Since we are going to manipulate the SysUser table then we will name the class as "UserManager". Here's the code block for the "UserManager.cs" class,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using WebAppDemo.Model.DB;  
  6.   
  7. namespace WebAppDemo.Model  
  8. {  
  9.     public class UserManager  
  10.     {  
  11.   
  12.         private DeveloperReportEntities dre = new DeveloperReportEntities();  
  13.   
  14.         public void Add(string firstName, string LastName, string contactNumber, string loginID, string password)  
  15.         {  
  16.             SysUser user = new SysUser();  
  17.             user.FirstName = firstName;  
  18.             user.LastName = LastName;  
  19.             user.ContactNumber = contactNumber;  
  20.             user.SysUserLoginID = loginID;  
  21.             user.SysPassword = password;  
  22.   
  23.             dre.AddToSysUsers(user);  
  24.             dre.SaveChanges();  
  25.         }  
  26.     }  
  27. }  
The code above handles the insertion of data to our database. The DeveloperReportEntities is the name of our object entity, which is the gateway to communicate with the data from the database. The SysUser is a class generated by EF which houses some properties. Calling the AddToSysUsers() method will add the new SysUser object that we have created. The AddToSysUsers() method is automatically created by EF for us. Invoking the SaveChanges() method automatically inserts the data to our database.

Performing Insert

Let’s start by performing an insert operation to our database. Now switch to WebForms’ code behind file, and create a new method that would call the UserManager class to do insertion. Here's the code block below:
  1. using System;  
  2. using WebAppDemo.Model;  
  3.   
  4. namespace WebAppDemo  
  5. {  
  6.     public partial class WebForm1 : System.Web.UI.Page  
  7.     {  
  8.   
  9.         private void InsertUserInfo(string firstName, string LastName, string contactNumber, string loginID, string password)  
  10.         {  
  11.             UserManager userMgr = new UserManager();  
  12.             userMgr.Add(firstName, LastName, contactNumber, loginID, password);  
  13.         }  
  14.   
  15.         protected void btnAdd_Click(object sender, EventArgs e)  
  16.         {  
  17.             //You may need to validate the data first here  
  18.              
  19.             InsertUserInfo(tbFirstName.Text,  
  20.                            tbLastName.Text,  
  21.                            tbContactNumber.Text,  
  22.                            tbLoginID.Text,  
  23.                            tbPassword.Text);  
  24.   
  25.             lblMessage.Text = "Data Inserted!";  
  26.   
  27.         }  
  28.     }  
  29. }  
Notice that we never included some basic validations in the form such as data inputs and data formats because we want to keep this demo as simple as possible. In real projects, you should ensure that all data inputs are validated before submitting it to the database, including the login ID and password validations.

Running the page will result to something like this:

page

And here's the screenshot of the SysUser table after the data is inserted:

data

Performing Fetch and Filter

In this section, we’re going to see how to fetch the data from the database and populate the form fields with Entity Framework.

Setting Up the Form

Okay. Let's go ahead and add a new WebForm page. Then setup the ASPX markup to something like this:
  1. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">  
  2.     <asp:DropDownList ID="ddlUser" runat="server" AppendDataBoundItems="true">  
  3.         <asp:ListItem Value="0">--Select--</asp:ListItem>  
  4.     </asp:DropDownList>  
  5.     <br />First Name:  
  6.     <br />  
  7.     <asp:TextBox ID="tbFirstName" runat="server" />  
  8.     <br />Last Name:  
  9.     <br />  
  10.     <asp:TextBox ID="tbLastName" runat="server" />  
  11.     <br />Contact Number:  
  12.     <br />  
  13.     <asp:TextBox ID="tbContactNumber" runat="server" />  
  14. </asp:Content>  
Again, there’s nothing fancy in the markup above. What we want to do here is we are going to populate the DropDownList "ddlUser" with the list of names from the database, and then populate the remaining textbox with the details based on the selected name from the DropDownList. Since we only want to display the information in the page, so we set the ReadOnly attribute in the TextBox to true.

Creating the View Model

If you remember, we created an Object Manager Class for handling any data operations in the database. Since we are going to fetch the list of names from the database, then we will add a new method in UserManager class.
As a recap, Entity Framework will generate the business objects and manage Data Access within the application. As a result, the class SysUser is automatically created by EF and it features all the fields in the database table as properties of the class.

We don't want to use this class for listing all names of the users. It would be wasteful as EF will bring back all information in the table including the LastName, ContactNumber, SysUserLogIn and Password. All we need for populating the DropDownList is the SysUserID and FirstName. Having that said, we need to create a separate class that just holds these properties:
  1. namespace WebAppDemo.Model.ViewModel  
  2. {  
  3.     public class UserName  
  4.     {  
  5.         public int SysUserID { getset; }  
  6.         public string FirstName { getset; }  
  7.     }  
  8. }  
We also need to create a separate class for listing the user detail information, and create the necessary fields that we need to use like below:
  1. public class UserDetail  
  2. {  
  3.     public int SysUserID { getset; }  
  4.     public string FirstName { getset; }  
  5.     public string Lastname { getset; }  
  6.     public string ContactNumber { getset; }  
Both classes above are stored under Model -> ViewModel folder within the application, as you can probably guess from the namespaces defined ;).

At this point, we already have the required fields for populating the controls in the form. Let now add a couple of new methods in UserManager class: (1) for fetching the list of names and, (2) for fetching the user details. Our UserManager class would now become like this:
  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using WebAppDemo.Model.DB;  
  4. using WebAppDemo.Model.ViewModel;  
  5.   
  6. namespace WebAppDemo.Model  
  7. {  
  8.     public class UserManager  
  9.     {  
  10.   
  11.         private DeveloperReportEntities dre = new DeveloperReportEntities();  
  12.   
  13.         public void Add(string firstName, string LastName, string contactNumber, string loginID, string password)  
  14.         {  
  15.             SysUser user = new SysUser();  
  16.             user.FirstName = firstName;  
  17.             user.LastName = LastName;  
  18.             user.ContactNumber = contactNumber;  
  19.             user.SysUserLoginID = loginID;  
  20.             user.SysPassword = password;  
  21.   
  22.             dre.AddToSysUsers(user);  
  23.             dre.SaveChanges();  
  24.         }  
  25.   
  26.         public IEnumerable<UserName> GetUserFirstName()  
  27.         {  
  28.             var user = from o in dre.SysUsers  
  29.                        select new UserName  
  30.                        {  
  31.                            SysUserID = o.SysUserID,  
  32.                            FirstName = o.FirstName  
  33.                        };  
  34.             return user.ToList();  
  35.         }  
  36.   
  37.         public IEnumerable<UserDetail> GetUserDetail(int userID)  
  38.         {  
  39.             var user = from o in dre.SysUsers  
  40.                        where o.SysUserID == userID  
  41.                        select new UserDetail  
  42.                        {  
  43.                            SysUserID = o.SysUserID,  
  44.                            FirstName = o.FirstName,  
  45.                            LastName = o.LastName,  
  46.                            ContactNumber = o.ContactNumber  
  47.                        };  
  48.             return user.ToList();  
  49.         }  
  50.   
  51.     }  
  52. }  
The code above used LINQ syntax for querying data. As you can see, we query the SysUser object based on the parameter we passed on the GetUserFirstName() method. Once we invoke the LINQ ToList() function, this LINQ query will issue a parameterize SQL query to the database in which the SQL Server can understand and then bring back the results to the Entity Model.

The GetUserFirstName() is a method that gets all the User FirstName along with the SysUserID. This method returns an IEnumrable of UserName class. The GetUserDetail() is a method that gets the user detail information based on the
ID passed on to the query. This method returns a List of UserDetail class.

One of the cool things about EF is we don’t need to worry about how the query is being constructed because EF will take care of that for you, including mapping of the data types from your table columns, mapping relationships between tables, etcetera and etcetera. Always keep in mind that EF is an ORM (Object Relational Mapper) and so we don’t need to deal directly with databases, tables and columns but instead we deal with the objects that is in the Entity and query the data against it using LINQ syntax.

Populating the DropDownList

Now let’s switch to the code behind file of the WebForm and populate the DropDownList. Here's the code block for binding the DropDownList control in the webform. Typically we do this at Page_Load event within Not IsPostBack block like below:
  1. using System;  
  2. using WebAppDemo.Model;  
  3.   
  4. namespace WebAppDemo  
  5. {  
  6.     public partial class WebForm2 : System.Web.UI.Page  
  7.     {  
  8.   
  9.         private void BindUserNames()  
  10.         {  
  11.             UserManager userMgr = new UserManager();  
  12.             ddlUser.DataSource = userMgr.GetUserFirstName();  
  13.             ddlUser.DataTextField = "FirstName";  
  14.             ddlUser.DataValueField = "SysUserID";  
  15.             ddlUser.DataBind();  
  16.         }  
  17.         protected void Page_Load(object sender, EventArgs e)  
  18.         {  
  19.             if (!IsPostBack)  
  20.                 BindUserNames();  
  21.         }  
  22.     }  
  23. }  
Running the page will result to something like this:

page

Populating the Form with the User Details

Now that we already have the list of first names in the DropDownList, the next step is to populate the TextBox in the form with other user information based on the selected item from the DropDownList. Here's the code block below:
  1. private void PopulateFormFieds(int userID)  
  2. {  
  3.     UserManager userMgr = new UserManager();  
  4.     var result = userMgr.GetUserDetail(userID);  
  5.     if (result.Count > 0)  
  6.     {  
  7.         var user = result.First();  
  8.         tbFirstName.Text = user.FirstName;  
  9.         tbLastName.Text = user.LastName;  
  10.         tbContactNumber.Text = user.ContactNumber;  
  11.     }  
  12.     else  
  13.     {  
  14.         //NO RECORDS FOUND.  
  15.         tbFirstName.Text = string.Empty;  
  16.         tbLastName.Text = string.Empty;  
  17.         tbContactNumber.Text = string.Empty;  
  18.     }  
  19. }  
  20.   
  21. protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)  
  22. {  
  23.     PopulateFormFieds(Convert.ToInt32(ddlUser.SelectedItem.Value));  
  24. }  
As you can see the code above is very straight forward. The PopulateFormFieds() is obviously a method for populating the TextBox with the user detail information. The first line in the method creates an instance of the UserManager class and calls the method GetUserDetail() by passing the userID as the parameter. We then stored the results in the result variable and check if the result count is greater than 0. If it is greater than 0 then that means there are data returned based on the query we issued, and fill the TextBox with the corresponding data.

Here's the output below after selecting an item from the DropDownList:

page

Performing Edit and Update

In this section, we are going to see how to Edit and Update the form with Entity Framework. Since this is a continuation of the previous section, then we’ll be using the same layout and extend it a bit by adding some server controls: Few Buttons and a Label control for displaying a message. Aside from that we also need to move the form fields inside a Panel control for validation purposes, and remove the ReadOnly attribute for each TextBox. Here's the updated mark-up below:
  1. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">  
  2.     <asp:DropDownList ID="ddlUser" runat="server" AppendDataBoundItems="true"  
  3.                       AutoPostBack="true" onselectedindexchanged="ddlUser_SelectedIndexChanged">  
  4.         <asp:ListItem Value="0">--Select--</asp:ListItem>  
  5.     </asp:DropDownList>  
  6.     <asp:Panel ID="pnlUserDetail" runat="server" Enabled="false">  
  7.         <br />First Name:  
  8.         <br /><asp:TextBox ID="tbFirstName" runat="server" />  
  9.         <br />Last Name:  
  10.         <br /><asp:TextBox ID="tbLastName" runat="server" />  
  11.         <br />Contact Number:  
  12.         <br /><asp:TextBox ID="tbContactNumber" runat="server" />  
  13.         <br />  
  14.         <br />  
  15.     </asp:Panel>  
  16.     <asp:Label ID="lblMessage" runat="server" ForeColor="Green" />  
  17.     <br />  
  18.     <asp:Button ID="btnEdit" runat="server" Text="Edit" onclick="btnEdit_Click" />  
  19.     <asp:Button ID="btnUpdate" runat="server" Text="Update" Visible="false" onclick="btnUpdate_Click" />  
  20.     <asp:Button ID="btnCancel" runat="server" Text="Cancel" Visible="false" onclick="btnCancel_Click" />  
  21.     <asp:Button ID="btnDelete" runat="server" Text="Delete" onclick="btnDelete_Click" />  
  22. </asp:Content>  
  23.  

Now, add the following method below in the UserManager class:
  1. public void UpdateUser(UserDetail userDetail)    
  2. {    
  3.     var user = (from o in dre.SysUsers    
  4.                 where o.SysUserID == userDetail.SysUserID    
  5.                 select o).First();    
  6.     user.FirstName = userDetail.FirstName;    
  7.     user.LastName = userDetail.LastName;    
  8.     user.ContactNumber = userDetail.ContactNumber;    
  9.     
  10.     dre.SaveChanges();    
  11. }    
 
The UpdateUser() method handles the updating of data. This method takes the UserDetail class as the parameter. If you can still remember in previous example, the UserDatail is a class that holds some properties such as the SysUserID, FirstName, LastName and ContactNumber.

The first line within the method gets the SysUser object based on the userID using LINQ syntax and assigned the result into a variable user. The LINQ FirstOrDefault() method is an eager function which returns the first element of a sequence that satisfies a specified condition. Once the FirstOrDefault() function is invoked, then EF will automatically issue a parameterize SQL query to the database in which the SQL Server can understand, and then bring back the result to the Entity Model.

We then assigned the new values to each field and then call SaveChanges() method to update the database with the changes.

Now let's go to the code behind file of the WebForm and perform the update by calling the method UpdateUser() from the UserManager class. Here are the code blocks below:
  1. private void ToggleButton(bool isEdit)  
  2. {  
  3.     if (isEdit)  
  4.     {  
  5.         btnEdit.Visible = false;  
  6.         btnDelete.Visible = false;  
  7.         btnUpdate.Visible = true;  
  8.         btnCancel.Visible = true;  
  9.     }  
  10.     else  
  11.     {  
  12.         btnEdit.Visible = true;  
  13.         btnDelete.Visible = true;  
  14.         btnUpdate.Visible = false;  
  15.         btnCancel.Visible = false;  
  16.     }  
  17.   
  18.     pnlUserDetail.Enabled = isEdit;  
  19. }  
  20.   
  21. private void UpdateUserDetail(UserDetail userDetail)  
  22. {  
  23.     UserManager userMgr = new UserManager();  
  24.     userMgr.UpdateUser(userDetail);  
  25. }  
  26.   
  27. protected void btnEdit_Click(object sender, EventArgs e)  
  28. {  
  29.     if (ddlUser.SelectedItem.Value != "0")  
  30.     {  
  31.         ToggleButton(true);  
  32.         lblMessage.Text = string.Empty;  
  33.     }  
  34.     else  
  35.     {  
  36.         lblMessage.Text = "Please select name from the list first.";  
  37.         lblMessage.ForeColor = System.Drawing.Color.Red;  
  38.     }  
  39. }  
  40.   
  41. protected void btnUpdate_Click(object sender, EventArgs e)  
  42. {  
  43.   
  44.     UserDetail userDetail = new UserDetail();  
  45.     userDetail.SysUserID = Convert.ToInt32(ddlUser.SelectedItem.Value);  
  46.     userDetail.FirstName = tbFirstName.Text.TrimEnd();  
  47.     userDetail.LastName = tbLastName.Text.TrimEnd();  
  48.     userDetail.ContactNumber = tbContactNumber.Text.TrimEnd();  
  49.   
  50.     UpdateUserDetail(userDetail);  
  51.     lblMessage.Text = "Update Successful!";  
  52.     ToggleButton(false);  
  53. }  
  54.   
  55. protected void btnCancel_Click(object sender, EventArgs e)  
  56. {  
  57.     ToggleButton(false);  
  58. }  
The ToggleButton() method returns a boolean type which is responsible for toggling the visibility of each buttons in the form during Edit, Update, Cancel and Delete mode.

The UpdateUserDetail() method takes a UserDetail as the parameter. This method calls the UpdateUser() method from the UserManager class.

At btnUpdate_Click event, we created an instance of the UserDetail class and assign the values from the form to the corresponding fields. After that, we call the method UpdateUserDetail() and pass the UserDetail object as the parameter.

Here's the output below when running it on the browser:

On initial load,

On initial load

After selecting an item from the DropDownList,

DropDownList  

On Edit Mode (after clicking the edit button) ,

Edit Mode

After Update,

 After Update

Performing Delete

Last but not the least; let’s implement the deletion part of the program. In the UserManager class, add the following method below:
  1. public void DeleteUser(int userID)  
  2. {  
  3.     var user = (from o in dre.SysUsers  
  4.                 where o.SysUserID == userID  
  5.                 select o).FirstOrDefault();  
  6.   
  7.     dre.DeleteObject(user);  
  8.     dre.SaveChanges();  
  9. }  
Just like the UpdateUser() method, we query the SysUser object based on the SysUserID and then assign the result in the variable user. After that, we called the DeleteObject() method to perform delete and then call the SaveChanges
() method to reflect the changes to the database.

Here's the code behind for the deletion:
  1. protected void btnDelete_Click(object sender, EventArgs e)  
  2. {  
  3.     if (ddlUser.SelectedItem.Value != "0")  
  4.     {  
  5.         //Perform the Delete  
  6.         UserManager userMgr = new UserManager();  
  7.         userMgr.DeleteUser(Convert.ToInt32(ddlUser.SelectedItem.Value));  
  8.   
  9.         //Re-bind the DropDownList  
  10.         ddlUser.Items.Clear();  
  11.         BindUserNames();  
  12.   
  13.         //Clear the form fields  
  14.         tbFirstName.Text = string.Empty;  
  15.         tbLastName.Text = string.Empty;  
  16.         tbContactNumber.Text = string.Empty;  
  17.   
  18.         lblMessage.Text = "Delete Successful!";  
  19.   
  20.     }  
  21.     else  
  22.     {  
  23.         lblMessage.Text = "Please select name from the list first.";  
  24.         lblMessage.ForeColor = System.Drawing.Color.Red;  
  25.     }  
  26. }  
Since we don’t want users to delete the information right away, we need to prompt them a confirmation message if they wish to continue the deletion or not. To do this, we could simply hook up the JavaScript confirm function to the delete button. Take a look at the highlighted code below:
  1. <asp:Button ID="btnDelete" runat="server" Text="Delete" onclick="btnDelete_Click" OnClientClick="return confirm('The selected user information will be deleted. Do you wish to continue?');return false;" /> 
Here's the output below when running the page and perform the delete:

On Delete

On Delete

After Deletion

After Deletion

That’s it! I hope someone find this article useful.

Summary

In this article, we have learned about the basics of how to perform Insert, Fetch, Filter, Edit, Update and Delete using ADO.NET Entity Framework.


Similar Articles