Add List of Item to Database using Entity Framework

Introduction

In this article we will see how to add list of item to database using entity framework.

Step 1: Create asp.net web application

 

WebForm1.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Adding_List_EntityFramework.WebForm1" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <asp:Button ID="Button1" runat="server" Text="Insert Data" OnClick="Button1_Click" />  
  13.     </div>  
  14.     </form>  
  15. </body>  
  16. </html>  

WebForm1.aspx.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. namespace Adding_List_EntityFramework  
  9. {  
  10.     public partial class WebForm1 : System.Web.UI.Page  
  11.     {  
  12.         protected void Page_Load(object sender, EventArgs e)  
  13.         {  
  14.   
  15.         }  
  16.   
  17.         protected void Button1_Click(object sender, EventArgs e)  
  18.         {  
  19.             EmployeeDBEntities context = new EmployeeDBEntities();  
  20.             List<Employee> employees = new List<Employee>()  
  21.             {  
  22.                 new Employee{FirstName="Andy", LastName="Jones"},  
  23.                 new Employee{FirstName="Steve", LastName="Robes"},  
  24.                 new Employee{FirstName="Dave", LastName="Robe"},  
  25.             };  
  26.   
  27.             foreach (Employee employee in employees)  
  28.             {  
  29.                 context.Employees.Add(employee);  
  30.             }  
  31.   
  32.             context.SaveChanges();  
  33.         }  
  34.     }  
  35. }  

Output of the application looks like this

Summary

In this blog we have seen how we can add list of items to database using entity framework. Happy coding!

Ebook Download
View all
Learn
View all
MVC Corporation is consulting and IT services based company.