Significance of SaveChanges:

SaveChanges method of ObjectContext is a gateway to persist all changes made to entities to the database. When you call ObjectContext.SaveChanges(), it performs insert, update or delete operation on the database based on EntityState of the entities.


Following code shows how you can persist modification made to the Student entities of SchoolDB EDM created either with EntityObject entities or POCO Proxy entities.

      //Update entity using SaveChanges method
      using (SchoolEntities ctx = new SchoolDBEntities())
                var stud = (from s in ctx.Students
                            where s.StudentName == "Student1"
                            select s).FirstOrDefault();

                stud.StudentName = "Student2";

                int num = ctx.SaveChanges();

As you can see in above code, we fetch the single Student entity whose name is “Student1” and then we change the StudentName property to “Student2”. It saves this modification to the database when we do ctx.SaveChanges(). This method also returns the number of rows updated in the database.


SaveChanges also accepts SaveOptions parameter. SaveOption is an Enum which has three values:

  1. AcceptAllChangesAfterSave: After saving entities values to the database, context change entity states. Added and Modified entities become Unchanged and deleted entities are removed from the context.

  2. DetectChangesBeforeSave: It tells context to detect changes before saving.
  3. None: Neither AcceptAllChangesAfterSave or DetectChangesBeforeSave occurs

So this way SaveChanges method is the most important method in the EntityFramework.


Remember: SaveChanges method persist modifications made to all entities attached to it. So for example in above code, if you fetch and modify ‘StudentAddress’ entity also and call ctx.SaveChanges() then it will save modification of Student and StudentAddress entities to the database.



Entity Framework