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.

  • 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.
  • Kill off the data context.
  • 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.
  • SaveChanges on that context. It will send an update to the persistance store eg SQL for that contact.
  • Kill the context.
  • 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.

    链接地址: http://www.djcxy.com/p/33562.html

    上一篇: 实体框架超时

    下一篇: 实体框架4保存并取消