Introduction

This article shows how to perform remove range operations using Entity Framework.

Create console application

Employee.cs

  1. namespace RemoveRangeEFApp
  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 RemoveRangeEFApp
  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 RemoveRangeEFApp
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. using (var objEmpContext = new EmployeeContext())
  13. {
  14. var employees = objEmpContext.Employees.Where(p => p.FirstName == "Syed").ToList();
  15. objEmpContext.Employees.RemoveRange(employees);
  16. objEmpContext.SaveChanges();
  17. }
  18. Console.ReadKey();
  19. }
  20. }
  21. }

The following is the output of the application:

Summary

In this article we saw how to do remove range operations using Entity Framework. Happy coding.