Delete Multiple Objects with Entity Framework

Updated on     Kisan Patel

This tutorial will show you 3 ways to delete multiple records from table with Entity Framework.

1. Using DbSet.RemoveRange(IEnumerable) Method

EntityFramework 6 provide a bit easier method DbSet.RemoveRange(IEnumerable) method. It will set each entity into the Deleted state such that it will be deleted from the database when SaveChanges is called.

context.Peoples.RemoveRange(db.People.Where(x => State == "CA"));
context.SaveChanges();

2. Using List<T>.ForEach Method

List<T>.ForEach method Performs the specified action on each element of the List<T>.

context.Peoples.Where(x => State == "CA").ToList().ForEach(x => context.Peoples.Remove(x));
context.SaveChanges();

3. Using SqlQuery method

The SqlQuery method on DbSet allows a native raw SQL query against the database using DbContext.

context.Database.SqlQuery(
  "DELETE FROM People WHERE State = @state",
  new [] { new SqlParameter("@state", "CA") }
);

C# Entity Framework

Leave a Reply