I flatter myself by suggesting that this comes from "the great minds think alike department", as Danny Simmons has written a blog showing how to do something that I am quite fond of - searching the ObjectContext for entities that are already in memory.
If you don't know EF very well, you might assume this is an obvious task, but unfortunately it's not.
The GetObjectByKey method will search first in the context but then go to the database if the entity is not already in there. What's bad about this is that there will be many people using this method not realizing that this is happening. That means a) you are hitting the db unexpectedly and b) you may be getting incorrect results if you were expecting only to be searching for what was already in memory.
The way to search *only* the cached entities is by searching the ObjectStateEntry objects that the context has created for each entity that it's managing. The ObjectStateEntry then gives you a pointer back to the entity object. Another nice thing is that you are not limited to searching by key. You can use GetObjectStateEntry to get a single entry based on it's EntityKey or get groups of entries with GetObjectStateEntries where you can search by EntityState, type and using the metadata, you can even filter by property values. Once you have the entries, you can then get back to their EntityObjects.
In Chapter 18 of my book I listed an extension method for doing this, but since Danny has written a great blog post on how to pull off this task, you should definitely take a look at it! “Local” Queries
It's not just a useful function, but a very necessary one. The good news is that we won't have to be so clever in the next version, which Danny also explains in this post.
Danny has been blogging up a storm lately, laying out a new iteration of his pet project, DPMud, with lots of fantastic lessons in it.




