1

I have an entity with a bunch of child entities as properties. Users are presented with a list of entities, can select one to modify it, then Save or Cancel the changes. Saving and Cancelling is not required to switch between entities, so its possible that more than one object is EntityState.Modified at once.

The Save button correctly works to save both the selected entity and all child entities, however the Cancel button is only reverting the changes made to the parent entity, without reverting changes to the child entities.

Is there an easy way to revert all changes within the graph for that object, without looping through every navigation property?

I am using the following code to revert the changes:

context.Connection.Open();
context.Refresh(RefreshMode.StoreWins, MyEntity);
context.Connection.Close();

A simplified sample of my entity class structure looks like this:

class MyEntity
{
    string Name;
    IList<Address> Addresses;
    IList<Contact> Contacts;
    IList<Note> Notes;
}

class Contact
{
    string Name;
    string Title;
    IList<EmailAddress> EmailAddresses;
    IList<Phone> PhoneNumbers;
}

I did see this question, however that solution would revert changes to all unsaved entities, and not just the selected entity.

Context.Refresh(RefreshMode.StoreWins, _
    Context.ObjectStateManager.GetObjectStateEntries());
Community
  • 1
  • 1
Rachel
  • 130,264
  • 66
  • 304
  • 490
  • I'm assuming you're reverting is in reference to the instance and not the database? Can you not just re-pull the data? – Bob. Nov 01 '12 at 19:28
  • @Bob. The entity is passed to my DAL by reference and is used in a few different places, so I want to maintain the reference to the existing entity instead of replacing it with a new instance of the entity entirely. – Rachel Nov 01 '12 at 19:30
  • I'm assuming its too big to be saved as a template so that you can use the template to revert changes? i.e. `Entity baseObj = referencedObj;` `instanceObj.ChildField = baseObj.ChildField;` – Bob. Nov 01 '12 at 19:37
  • I don't think there is. Maybe, if you can still revise the code, you should prevent the entities from getting modified in the first place, i.e. by using a view model/DTO and replaying the changes in the domain. Although that would involve more than one call as well. – Gert Arnold Nov 02 '12 at 21:09

0 Answers0