Deleting Multiple Records in Entity Framework | Entity Framework Tutorial

Sometimes you may need to delete multiple records. In such case, developers use to iterate through the collection using foreach and will set each entity state to modified. Some developers use to write an extension method as below to handle deleting multiple records in entity framework.

Extension Method:

public static void DeleteObjects(this ObjectSet set, Expression> predicate) where T : EntityObject { foreach (var entity in set.AsQueryable().Where(predicate)) set.DeleteObject(entity); }

Usage of Extension Method

db.Employees.DeleteObjects(x => x.Country == "India");

However to make the life of the .Net developer easier, entity framework 6 has introduced a method named RemoveRange to delete multiple records at one shot as given in the below code snippet:

db.People.RemoveRange(db.Employees.Where(x => Country == "India"));