EntityFramework 学习 一 Persistence in Entity Framework
实体框架的持久化
当用EntityFramework持久化一个对象时,有两种情形:连接的和断开的
1.连接场景:使用同一个context上下文从数据库中查询和持久化实体时,查询和持久化实体期间,context不会被销毁
2.断开场景:实体的查询和保存提交使用不同的context上下文
上图所示,context1查询数据库中的实体然后被销毁,当实体变化时,应用程序使用context2来提交
这种情形是复杂的,因为新的context上下文不知道实体的变化,所以你不得不通知上下文。
CRUD Operation in Connected Scenario:连接状态下的CRUD操作
using (var context = new SchoolDBEntities()) { var studentList = context.Students.ToList<Student>(); //Perform create operation context.Students.Add(new Student() { StudentName = "New Student" }); //Perform Update operation Student studentToUpdate = studentList.Where(s => s.StudentName == "student1").FirstOrDefault<Student>(); studentToUpdate.StudentName = "Edited student1"; //Perform delete operation context.Students.Remove(studentList.ElementAt<Student>(0)); //Execute Inser, Update & Delete queries in the database context.SaveChanges(); }
注意:如果
context.Configuration.AutoDetectChangesEnabled = false
如果该属性设置为false,context不能检测到存在实体的变化,所以不能执行更新操作,你不得不在调用SaveChanges()之前调用context.ChangeTracker.DetectChanges()
当addingdeleting在DBSet上操作实体时,上下文检测这些操作,如果在分离的集合或list上进行这些操作,上下文将不检测这些变化
using (var context = new SchoolDBEntities()) { var studentList = context.Students.ToList<Student>(); //Add student in list studentList.Add(new Student() { StudentName = "New Student" }); //Perform update operation Student studentToUpdate = studentList.Where(s => s.StudentName == "Student1").FirstOrDefault<Student>(); studentToUpdate.StudentName = "Edited student1"; //Delete student from list if (studentList.Count > 0) studentList.Remove(studentList.ElementAt<Student>(0)); //SaveChanges will only do update operation not add and delete context.SaveChanges(); }
总结:
context.Configuration.AutoDetectChangesEnabled = false
如果在
context.SaveChanges();之前不调用context.ChangeTracker.DetectChanges() 则实体的更新操作不发送到数据库中运行更新,
不过实体的删除和添加都会发送到数据库中运行
如果Add 和 delete不在DbSet上操作,则不会在数据库中添加删除实体,而仅仅在数据库中更新实体