I'm having trouble saving changes made to my POCO's back into the database.
When the application starts, I grab all the objects I need into POCO objects, then when I click the "Save" button, I create a new ObjectContext instance, I then have to loop the objects, attach them to the context, and then detect changes and save.
public void SaveData() {
using (SolEntities sec = new SolEntities(_cxnStr)) {
foreach (ExtViews.Planet p in Planets) {
sec.CelestialBodies.Attach(p.TheBody);
sec.CelestialBodies.ApplyCurrentValues(p.TheBody);
}
sec.SaveChanges(SaveOptions.AcceptAllChangesAfterSave | SaveOptions.DetectChangesBeforeSave);
}
}
But this doesn't seem to work, the 2 ways I could get it to work was to either:
A) Create a local list of Planets before the foreach
loop (to force them to be generated from the Db before applying the changed values I presume), and remove the Attach
satement.
or
B) Switch the ApplyCurrentValues
line for this one:
sec.ObjectStateManager.ChangeObjectState(p.TheBody, System.Data.EntityState.Modified);
But manually forcing the ObjectState to modified for every object seems a bit overkill, especially if they've not been modified, I could keep something internally of whether it's been modified or not, but I thought that ApplyCurrentValues would do so in the first place?