开发者

Saving POCO changes

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 t开发者_StackOverflow社区o 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?


Poco objects can not track changes. Only entity derived objects can track changes or else you have to either generate self tracking objects or derive your poco objects from your custom class which will track the changes.

You can hook for your own object's property changed event or generate code in such a way to store your changes with some local repository which you can empty if your submit changes was successful.


msdn - suggest to use,

context.ObjectStateManager.TryGetObjectStateEntry(newItem, out entry);

Also have look at Snapshot based Change tracking.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜