Reflect all changes to ObjectContext without saving the database

Since it ObjectContext.SaveChanges()

happens inside a transaction, I decided that it would be best for my application to do all the requests / updates in the ObjectContext

pre-call SaveChanges()

once to write the data to the database.

However, this means that if I create an object and submit to the request ObjectContext

, it denies its existence (presumably because the database hasn't been updated yet). I assumed I could work around this with some SaveOptions , but it doesn't seem like I can.

Basically I want to ObjectContext

act like a proxy that I can change as I want it all in one go. Is there a way I can achieve this?

+3


source to share


2 answers


If you do not save your changes, your new objects will not exist in the database, and no query made against the database query (= no Linq for objects) will return them. In order for objects to be added to the context, but not saved, you must request ObjectStateManager

:



var data = context.ObjectStateManager
                  .GetObjectStateEntries(EntityState.Added)
                  .Where(e => !e.IsRelationship)
                  .Select(e => e.Entity)
                  .OfType<YourEntityType>();

      

+6


source


I needed to do something along these lines in a similar situation:

Given a list of keys and values, when some of them are new and want to update / insert keys and values ​​into one SaveChanges

, I pull out all existing keys first and then maintain a separate collection keysIncludingNewOnes

that starts with only existing keys but also adds everything to it newly generated keys.



Then, when I search for a key object to associate with a value, I look keysIncludingNewOnes

instead of asking for the context, since (as you already found) the context doesn't know about the new keys until a SaveChanges

.

It should be relatively easy for you to remember your "pending addition" objects; if not, you may have an overly long-lived context that as a whole creates problems of its own.

0


source







All Articles