Entity Framework 6 introduced methods to add and remove a collection of entities in one go.
The DbSet.AddRange()
method attaches a collection of entities to the context with Added state, which will execute the INSERT command in the database for all entities on SaveChanges()
.
In the same way, the DbSet.RemoveRange()
method attaches a collection of entities with Deleted state, which in turn will execute the DELETE command for all entities on SaveChanges()
.
Adding or removing entities using the AddRange
and RemoveRange
methods improves the performance.
It is recommended to use these methods if you want to insert or delete a 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
methods by executing the INSERT and DELETE commands for all entities in a single database round trip.