Context.SaveChanges() in LINQ
.net, c#, linq
Solution
You can call `Context.SaveChanges();` once after all the updates and it will save all the changes done previously.
If you are expecting to change/insert a new object, and wants to modify the next objects based on the database's actual value, you may call `Context.SaveChanges()` so that the database gets updated.
Any changes/insertion to the entities are tracked in the context and once `SaveChanges` is called, it put the changes in the database as well.
Also keep this in mind: From MSDN:
SaveChanges operates within a transaction. SaveChanges will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted.
Problem
This is an easy question and I want to confirm with you experts! I am changing some values in two different tables in same database. Is it okay to just call SaveChanges one time to update all? Seems to work but I want to know if its okay or need to call context.SaveChanges after every update? ``` bool success = false; TestSuiteDB context = new TestSuiteDB(); var workstyle1 = context.WorkStyle.Where(d => d.WorkStyleId==21 && d.MemberId==1).ToList(); foreach (var ws1 in workstyle1) { ws1.ModuleId = flid1; } var workstyle2 = context.WorkStyle.Where(d => d.WorkStyleId == 22 && d.MemberId==1).ToList(); foreach (var ws2 in workstyle2) { ws2.ModuleId = flid2; } var workstylemodules1 = context.WorkStyleModules.Where(d => d.WorkStyleModuleId == 2 && d.MemberId == 1).ToList(); foreach (var ws1 in workstylemodules1) { ws1.ModuleId = flid1; } var workstylemodules2 = context.WorkStyleModules.Where(d => d.WorkStyleModuleId == 3 && d.MemberId == 1).ToList(); foreach (var ws2 in workstylemodules2) { ws2.ModuleId = flid2; } if (context.SaveChanges() > 0) { success = true; } ```