EF 4: How to update a disconnected dataset?

I am using EF 4, POCO. The task is as follows: to have a long data set of the DomainObject type, which must be taken from the database and updated (add, update, delete operations) in disconnected mode. How can I push the updated set back to the database later? Suppose that when loading data there were no parallel changes to the table. I know context.SaveChanges () does the update, but the question is how to return all changes back to DbSet from a kind of list, or maybe there is a way to directly work with DbSet in disconnected mode? Thanks!

+4
source share
2 answers

Self-test objects are a feature of the EDMX + ObjectContext API, so if you have a mapping / code dependent on the DbContext API (you mentioned DbSet ), you cannot use them. The objects of self-observation are the implementation of a change set template (for example, an old data set). Some link to SO:

If you do not use self-control objects, the answer is quite simple - you have to tell EF what changes you made. After using individual objects, you must attach the entities to the new context and manually specify exactly what you did = what is inserted, updated, deleted, and how you changed the relationship. A key component of this process is the ObjectStateManager in the ObjectContext API ( context.ObjectStateManager ) or the DbChangeTracker in the DbContext API ( context.ChangeTracker ). This is very difficult when we are dealing with relationships, so many of us usually use a different process: we reload the graph of objects and merge the changes from the graph of an individual object to the attached graph of objects. Some links:

Remember that your entire process can be quite slow depending on the number of updates you want to make. The reason is that EF does not support batch command , so each insert, update, delete is performed on a separate round trip to the database. If you upgrade 100,000 complex objects, you can expect SaveChanges take several minutes to complete.

Edit:

In some very special scenarios where you only work with objects without relationships, you can use the trick to convey information about the “changes”:

 public void ProcessChanges(IEnumerable<DomainObject> entities) { foreach(var entity in entities) { if (entity.Id == 0) { // New entity } else if (entity.Id > 0) { // Modified entity (you cannot say if entity war really modified, // you must update it always). } else { // Use negative Id (origId * -1) to mark entity as deleted // reverse Id and delete entity } } } 

This only works for flat objects with a simple key.

+7
source

All Articles