Introduction
This article shows how to perform remove range operations using Entity Framework.
Create console application
Employee.cs
- namespace RemoveRangeEFApp
- {
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Data.Entity.Spatial;
- [Table("Employee")]
- public partial class Employee
- {
- public int Id { get; set; }
- [StringLength(50)]
- public string FirstName { get; set; }
- [StringLength(50)]
- public string LastName { get; set; }
- }
- }
Employeecontext.cs
- namespace RemoveRangeEFApp
- {
- using System;
- using System.Data.Entity;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Linq;
-
- public partial class EmployeeContext : DbContext
- {
- public EmployeeContext()
- : base("name=EmpConn")
- {
- }
-
- public virtual DbSet<Employee> Employees { get; set; }
-
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- modelBuilder.Entity<Employee>()
- .Property(e => e.FirstName)
- .IsUnicode(false);
-
- modelBuilder.Entity<Employee>()
- .Property(e => e.LastName)
- .IsUnicode(false);
- }
- }
- }
Web.config
- <connectionStrings>
- <add name="EmpConn" connectionString="data source=WIN-B4KJ8JI75VF;initial catalog=EmployeeDB;user id=sa;password=India123;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
- </connectionStrings>
Program.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace RemoveRangeEFApp
- {
- class Program
- {
- static void Main(string[] args)
- {
- using (var objEmpContext = new EmployeeContext())
- {
- var employees = objEmpContext.Employees.Where(p => p.FirstName == "Syed").ToList();
- objEmpContext.Employees.RemoveRange(employees);
- objEmpContext.SaveChanges();
- }
-
- Console.ReadKey();
- }
- }
- }
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.