Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. Exploring EDM Queries in Grea... > Retrieving a Single Entity with GetO...

4.10. Retrieving a Single Entity with GetObjectByKey

The ObjectContext.GetObjectByKey method and its counterpart, TryGetObjectByKey, provide a way to query for an object without having to construct and execute a query. However, this has a notable twist. The runtime will first look in the existing instantiated objects to see whether the object has already been retrieved. If it is found, this is what will be returned. If not, the query to the data store will be executed automatically and the object will be returned.

GetObjectByKey takes an EntityKey type that defines what object to retrieve based on its EntitySet, its key property name, and the value of that property. For example, EntityKey("PEF.Contacts","ContactID",5) defines an object in the Contacts EntitySet with a ContactID value of 5. Once the EntityKey has been created, GetObjectByKey(myEntityKey) will return the object either from memory or from the database.

TryGetObjectByKey uses the .NET Try pattern to avoid returning an exception if the object is not found in memory or in the database.

You will see both of these used many times in later chapters, and you will learn all about the EntityKey class in Chapter 9.