代码改变世界

Entity Framework 6.0 Tutorials(7):DbSet.AddRange & DbSet.RemoveRange

2016-07-07 11:48  追忆似水流年  阅读(767)  评论(0编辑  收藏  举报

DbSet.AddRange & DbSet.RemoveRange:

DbSet in EF 6 has introduced new methods AddRange & RemoveRange. DbSet.AddRange adds collection(IEnumerable) of entities to the DbContext, so you don't have to add each entity individually.

IList<Student> newStudents = new List<Student>();
newStudents.Add(new Student() { StudentName = "Student1 by addrange" });
newStudents.Add(new Student() { StudentName = "Student2 by addrange" });
newStudents.Add(new Student() { StudentName = "Student3 by addrange" });
               
using (var context = new SchoolDBEntities())
{
    context.Students.AddRange(newStudents);
    context.SaveChanges();
}

 

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

IList<Student> existingStudents = …..
    
using (var context = new SchoolDBEntities())
{
    context.Students.RemoveRange(existingStudents);
        context.SaveChanges();
}

 

Download sample project for DbSet.AddRange demo.