DbSet.AddRange and DbSet.RemoveRange in Entity Framework 6.0

Entityframework 6.0 has introduced two new methods for Dbset: AddRange andRemoveRange. DbSet.AddRange adds the collection of entities to the DbContext, sowe don't have to add each entity individually.

 

Example

  1. using (SQLLogging.Model.Model context = new SQLLogging.Model.Model())  
  2. {  
  3.     List<Employee> employees = new List<Employee>();  
  4.     employees.Add(new Employee { Code = "PPP", Name = "Test - P" });  
  5.     employees.Add(new Employee { Code = "QQQ", Name = "Test - Q" });  
  6.     employees.Add(new Employee { Code = "RRR", Name = "Test - R" });  
  7.    
  8.     context.Employees.AddRange(employees);  
  9.     context.SaveChanges();  
  10. }  

Similarly,DbSet.RemoveRange is used to remove collection of entities from DbSet.

 

Example

  1. using (SQLLogging.Model.Model context = new SQLLogging.Model.Model())  
  2. {  
  3.     var employees = context.Employees.Where(p => p.Id >= 4).ToList();  
  4.     context.Employees.RemoveRange(employees);  
  5.    
  6.     context.SaveChanges();  
  7. }