Fetch, Insert, Update, Delete Data with “Database First Model Approach” using ADO.NET Entity Framework 3.5 and Visual Studio 2008.

In this article, you will learn how to Fetch, Insert, Update, and Delete Data using the "Database First Model Approach" and the ADO.NET Entity Framework 3.5 and Visual Studio 2008.
 
What is Entity Framework?
  1. Entity Framework is an Object/Relational Mapping (O/RM) framework.
  2. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in a database and working with the results in addition to Data Reader and DataSet.
  3. An Entity Framework Model (ERM) defines a schema of entities and their relationships with one another.
  4. Entities are not the same as objects.
  5. Entities define the schema of an object, but not its behavior.
  6. So, an entity is something like the schema of a table in your database, except that it describes the schema of your business objects.
  7. Entity Framework 3.5 supports the Database First model.

DATABASE FIRST MODEL

 
REQUIREMENTS
 
For implementing the Database First model, you need to download and install the Microsoft .NET Framework 3.5 Service Pack 1. You can download this from the following link:
 
http://www.microsoft.com/en-us/download/details.aspx?id=22
 
CREATE TABLE
  1. You need to create a table for implementing the Database First model.
  2. I have used the employee table for this tutorial.
  3. You can use the following employee table script to create a table.
  1. USE[Test]  
  2. GO  
  3. SET ANSI_NULLS ON  
  4. GO  
  5. SET QUOTED_IDENTIFIER ON  
  6. GO  
  7. SET ANSI_PADDING ON  
  8. GO  
  9. CREATE TABLE[dbo]. [Employee](  
  10.     [id][int] IDENTITY(1, 1) NOT NULL,  
  11.     [name][varchar](50) NULL,  
  12.     [address][varchar](50) NULL,  
  13.     CONSTRAINT[PK_Employee] PRIMARY KEY CLUSTERED(  
  14.         [id] ASC  
  15.     ) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON[PRIMARY]  
  16. ON[PRIMARY]  
  17. GO  
  18. SET ANSI_PADDING OFF  
  19. GO  
  20. SET IDENTITY_INSERT[dbo]. [Employee] ON  
  21. INSERT[dbo]. [Employee]([id], [name], [address]) VALUES(1, N 'Employee One', N 'Address One')  
  22. INSERT[dbo]. [Employee]([id], [name], [address]) VALUES(2, N 'Employee Tow', N 'Address Two')  
  23. INSERT[dbo]. [Employee]([id], [name], [address]) VALUES(3, N 'Employee Three', N 'Address Three')  
  24. SET IDENTITY_INSERT[dbo]. [Employee] OFF 
GENERATING MODEL FROM DATABASE
  1. Create a new "Employee" Web site in Visual Studio 2008.
  2. In the Solution Explorer, right-click on the project and choose "Add New Item".
     
    Image 1.jpg
     
  3. It will open an "Add New Item" dialog box. Choose the "ADO.NET Entity Data Model" and change the default name from "Model.edmx" to "Employee.edmx". Then click on the "Add" button.
     
    Image 2.jpg
     
  4. After clicking on the Add button, this will open the "Entity Data Model Wizard".
     
    Image 3.jpg
     
  5. In the wizard choose "Generate from database" and click on the "Next" button.
  6. Here you have two options. One is you can choose the existing SQL connection and another option is you can create your own SQL connection.
     
    Image 4.jpg
     
  7. For a new connection, click on the "New Connection" button. It will open the "Connection properties" window. Fill in all the details and click on the "OK" button. The new connection will be shown in the Entity Data Model Wizard.
     
    Image 5.jpg
     
  8. Click on "Yes, include the sensitive data in the connection string." and click on the "Next" button.
     
    Image 6.jpg
     
  9. Choose the required tables and name the Model Namespace as "EmployeeModel".
  10. Click on the "Finish" button. The model will be generated and opened in the EDM Designer.
     
    Image 7.jpg
CREATE A GRIDVIEW TO MANAGE THE DATA
 
1. Open the default.aspx page and add the grid view as below:
  1. <asp:GridView ID="grdEmployeeData" AutoGenerateColumns="False" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">  
  2.      <RowStyle BackColor="#EFF3FB" />  
  3.      <Columns>  
  4.           <asp:TemplateField HeaderText="Employee ID">  
  5.                <ItemTemplate>  
  6.                     <%# Eval("id") %>  
  7.                </ItemTemplate>  
  8.           </asp:TemplateField>  
  9.           <asp:TemplateField HeaderText="Employee Name">  
  10.                <ItemTemplate>  
  11.                     <%# Eval("name")%>  
  12.                </ItemTemplate>  
  13.           </asp:TemplateField>  
  14.           <asp:TemplateField HeaderText="Employee Adress">  
  15.                <ItemTemplate>  
  16.                     <%# Eval("address")%>  
  17.                </ItemTemplate>  
  18.           </asp:TemplateField>  
  19.      </Columns>  
  20.      <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />  
  21.      <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />  
  22.      <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />  
  23.      <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />  
  24.      <EditRowStyle BackColor="#2461BF" />  
  25.      <AlternatingRowStyle BackColor="White" />  
  26. </asp:GridView> 
2. Go to the "default.aspx.cs" page.
 
3. Include the namespace at the top of the page. This namespace will be given from the "Model Namespace" from Step 8.
  1. using EmployeeModel; 
DISPLAY DATA IN THE GRIDVIEW
 
The following code will help to display the data in the grid view.
  1. private void getData() {  
  2.     //Here TestEntities is the class which is given from "Save entity connection setting in web.config"  
  3.     TestEntities context = new TestEntities();  
  4.   
  5.     var query = from data in context.Employee  
  6.     orderby data.name  
  7.     select data;  
  8.   
  9.     //Bind Data to Gridview  
  10.     grdEmployeeData.DataSource = query;  
  11.     grdEmployeeData.DataBind();  

Output
 
Image 8.jpg
 
INSERT DATA IN THE EMPLOYEE TABLE
 
Use the following code to add the new employee: 
  1. private void insertData() {  
  2.     //Here TestEntities is the class which is given from "Save entity connection setting in web.config"  
  3.     TestEntities context = new TestEntities();  
  4.   
  5.     // Create a new employee  
  6.     Employee objEmployee = new Employee();  
  7.     objEmployee.name = "Employee Four";  
  8.     objEmployee.address = "Address Four";  
  9.   
  10.     //Add the created Employee object to the context.  
  11.     context.AddToEmployee(objEmployee);  
  12.     context.SaveChanges();  

Output
 
Image 9.jpg
 
UPDATE DATA IN THE DATABASE
 
You can use the following code to update the employee details:
  1. public void updateData() {  
  2.     //Here TestEntities is the class which is given from "Save entity connection setting in web.config"  
  3.     TestEntities context = new TestEntities();  
  4.   
  5.     var query = from data in context.Employee orderby data.name select data;  
  6.   
  7.     foreach(Employee details in query) {  
  8.         if (details.id == 1) {  
  9.             //Assign the new values to name whose id is 1  
  10.             details.name = "Updated Employee One";  
  11.         }  
  12.     }  
  13.   
  14.     //Save the changes back to the database.  
  15.     context.SaveChanges();  

Output
 
Image 10.jpg
 
DELETE THE EMPLOYEE DETAILS FROM DATABASE
 
You can use the following code to delete the employee details from the database:
  1. public void deleteData() {  
  2.     //Here TestEntities is the class which is given from "Save entity connection setting in web.config"  
  3.     TestEntities context = new TestEntities();  
  4.   
  5.     var query = (from data in context.Employee where data.id == 1 orderby data.name select data).First();  
  6.   
  7.     context.Attach(query);  
  8.     //DeleteObject is used to delete the entity object.  
  9.     context.DeleteObject(query);  
  10.     context.SaveChanges();  

OUTPUT
 
Image 11.jpg


Similar Articles