Share via


To query the local object context

When faced with the dilemma that what if I wanted to insert something and before I actually saved the changes into a persistent storage (database) by calling SaveAllChanges() method on the data context, I wanted to do a select, and also I wanted to make sure that this select is done on the just inserted objects, what should I be doing?

Well generally we write a generic method that gets all the records for a generic object. it looks like this:

IQueryable<T> result = null;

string type = typeof(T).Name;

//ObjectQuery query = entities.CreateQuery<T>(type);

ObjectQuery query = Context.CreateQuery<T>(type);

result = (

IQueryable<T>)query;

return result;

This will only query into the database. So if you have just recently inserted some records, but haven't yet committed them, they won’t appear in the results.

However, if we provide another method (an overload perhaps) that handles local objects, this would be possible. When I say local objects, I mean objects that have been inserted into the Object Context and yet not been persisted into the database. this method would look something like this:

IQueryable

<T> result = null;

string type = typeof(T).Name;

return from stateEntry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added |

EntityState.Modified |

EntityState.Unchanged)

where stateEntry.Entity != null && stateEntry.EntitySet.Name == type

select stateEntry.Entity as T;

This way we give the option to the user of the API to choose which kind of select he wants to fire. A local one or one on the database.