ObjectContext.GetObjectByKey Method
Returns an object that has the specified entity key.
Namespace: System.Data.Objects
Assembly: System.Data.Entity (in System.Data.Entity.dll)
Parameters
- key
- Type: System.Data.EntityKey
The key of the object to be found.
| Exception | Condition |
|---|---|
| ArgumentNullException | The key parameter is null. |
| ObjectNotFoundException | The object is not found in either the ObjectStateManager or the data source. |
GetObjectByKey tries to retrieve an object that has the specified EntityKey from the ObjectStateManager. If the object is currently not loaded into the object context, a query is executed in an attempt to return the object from the data source. For more information, see Object Queries (Entity Framework).
GetObjectByKey raises an ObjectNotFoundException when the object cannot be found. To avoid handling this exception, instead use the TryGetObjectByKey method.
This method will return objects in the Deleted state.
A temporary key cannot be used to return an object from the data source.
This example is based on the Adventure Works Sales Model. The example creates an EntityKey for an entity of the given type and then fetches an entity by key.
using (AdventureWorksEntities context = new AdventureWorksEntities()) { try { // Define the entity key values. IEnumerable<KeyValuePair<string, object>> entityKeyValues = new KeyValuePair<string, object>[] { new KeyValuePair<string, object>("SalesOrderID", 43680) }; // Create the key for a specific SalesOrderHeader object. EntityKey key = new EntityKey("AdventureWorksEntities.SalesOrderHeaders", entityKeyValues); // Get the object from the context or the persisted store by its key. SalesOrderHeader order = (SalesOrderHeader)context.GetObjectByKey(key); Console.WriteLine("SalesOrderID: {0} Order Number: {1}", order.SalesOrderID, order.SalesOrderNumber); } catch (ObjectNotFoundException ex) { Console.WriteLine(ex.ToString()); } }
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.