简体   繁体   中英

Entity Framework 4 Save and Cancel

I'm currently testing the entity framework 4 for a simple app I wish to build.

I've searched high and low for the answer to this without any luck!!

My question is how do you save and cancel changes on a record basis? Using the save changes method on the context persists all the changes to the database. Is there a way to control this?

Thanks Gary

You shouldn't use a singular Data Context for all the operations in the lifetime of your application. Spin up a session (create a Data Context) for each atomic operation you want to make. Call SaveChanges to submit the operation, simply dispose of the context without saving changes to 'cancel' the operation.

Sounds like you want to work in a disconnected fashion.

  1. Load all your employees from a data context using the NoTracking option. This will load the entities and immediately disconnect them from the data context.
  2. Kill off the data context.
  3. When you hit save, create a new data context and attach the contact you wish to save to the new data context; you will have the ability to mark the contact as modified.
  4. SaveChanges on that context. It will send an update to the persistance store eg SQL for that contact.
  5. Kill the context.
  6. Go to step 3.

You might also want to look into different EF templates such as self tracking entities which may make your life a bit easier as they generate entities which can track changes themselves outside of a data context; however this might be overkill for a simple app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM