Add or Remove Multiple Entities in Entity Framework:

Entity Framework 6 introduced methods to add or remove collection of entities in one go. The DbSet.AddRange() method attaches a collection of entity to the context with Added state, which will execute INSERT command in the database for all entities on SaveChanges(). The same way, DbSet.RemoveRange() method attaches a collection of entity with Deleted state, which in turn will execute DELETE command for all entities on SaveChanges().

Adding or removing entities using AddRange and RemoveRange methods improves the performance. It is recommended to use this methods if you want to insert or delete large number of records from the database using Entity Framework.

The following example demonstrates saving multiple entities.

IList<Student> newStudents = new List<Student>() {
                                    new Student() { StudentName = "Steve" };
                                    new Student() { StudentName = "Bill" };
                                    new Student() { StudentName = "James" };
                                };               

using (var context = new SchoolDBEntities())
{
    context.Students.AddRange(newStudents);
    context.SaveChanges();
}

The following example demonstrates removing multiple entities.

IList<Student> studentsToRemove = new List<Student>() {
                                    new Student() { StudentId = 1, StudentName = "Steve" };
                                    new Student() { StudentId = 2, StudentName = "Bill" };
                                    new Student() { StudentId = 3, StudentName = "James" };
                                };
    
using (var context = new SchoolDBEntities())
{
    context.Students.RemoveRange(studentsToRemove);
    context.SaveChanges();
}

Note: EF Core improves the performance of AddRange and RemoveRange method by executing INSERT and DELETE commands for all entities in a single database round trip.