fnx
fnx

Reputation: 491

Undo changes in Entity Framework including changed to object-references

There are several ways to undo changes in Entity Framework:

The application has a tabbed interface, where one tab is displaying a different entity-object. The user can add Tags to objects (m:n relationship). I tried everything I could find, I couldn't get Entity Framework undo changes that the user makes to the m:n relationship. For example the user adds a Tag (m:n object is created). If the user clicks "Cancel" the object should be saved to the database.

Recreating the context would potentially lead to losing data in other tabs. Detach/Attach and Refresh() works only if the object itself was changed and no related Objects where added/removed from the object's Lists.

I thought about using different context-objects for each tab, but that would lead to data being out of sync (for example the user clicks on a list and a new tab opens. After changing the the object, the list wouldn't be updated automatically)

Upvotes: 3

Views: 1404

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364399

There is no undo changes in EF. Your current problem is more about the way how your application is expected to work and how EF is expected to work. EF is expected to work as unit of work - you made a lot of changes and either save them together or throw them away together.

Your application obviously expects different model because you need to revert only part of changes. That is not exactly what EF's context is supposed to handle. Such logic should be handled separately from EF = your gui should work with objects not attached to context and you should attach entities and define changes only when user decides to save the result.

Partial undo in context requires you to browse entries in ObjectStateManager and revert created changes. For changed many-to-many relation you will have to find state entries representing relations and revert state changes. These entries can be only in added, deleted or unchanged states. You can move deleted back to unchanged but I'm at the moment not sure if you can somehow detach or remove added instances.

Upvotes: 2

Related Questions