Introduction

In this blog we will see how to perform add range operation using entity framework.

Step 1: Create console application

Employee.cs

  1. namespace AddRangeEFApp
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.ComponentModel.DataAnnotations.Schema;
  7. using System.Data.Entity.Spatial;
  8. [Table("Employee")]
  9. public partial class Employee
  10. {
  11. public int Id { get; set; }
  12. [StringLength(50)]
  13. public string FirstName { get; set; }
  14. [StringLength(50)]
  15. public string LastName { get; set; }
  16. }
  17. }

Employeecontext.cs

  1. namespace AddRangeEFApp
  2. {
  3. using System;
  4. using System.Data.Entity;
  5. using System.ComponentModel.DataAnnotations.Schema;
  6. using System.Linq;
  7. public partial class EmployeeContext : DbContext
  8. {
  9. public EmployeeContext()
  10. : base("name=EmpConn")
  11. {
  12. }
  13. public virtual DbSet<Employee> Employees { get; set; }
  14. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  15. {
  16. modelBuilder.Entity<Employee>()
  17. .Property(e => e.FirstName)
  18. .IsUnicode(false);
  19. modelBuilder.Entity<Employee>()
  20. .Property(e => e.LastName)
  21. .IsUnicode(false);
  22. }
  23. }
  24. }

Web.config

  1. <connectionStrings>
  2. <add name="EmpConn" connectionString="data source=WIN-B4KJ8JI75VF;initial catalog=EmployeeDB;user id=sa;password=India123;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  3. </connectionStrings>

Program.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace AddRangeEFApp
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. IList<Employee> newEmployee = new List<Employee>();
  13. newEmployee.Add(new Employee() { FirstName = "Jon", LastName = "Aw" });
  14. newEmployee.Add(new Employee() { FirstName = "Syed", LastName = "Khan" });
  15. newEmployee.Add(new Employee() { FirstName = "James", LastName = "Still" });
  16. using (var objEmpContext = new EmployeeContext())
  17. {
  18. objEmpContext.Employees.AddRange(newEmployee);
  19. objEmpContext.SaveChanges();
  20. }
  21. Console.ReadKey();
  22. }
  23. }
  24. }

Output of the application looks like this

Summary

In this blog we have seen how we can perform add range operation using entity framework. Happy coding!