ObjectContext.GetObjectByKey(EntityKey) ObjectContext.GetObjectByKey(EntityKey) ObjectContext.GetObjectByKey(EntityKey) ObjectContext.GetObjectByKey(EntityKey) Method


Returns an object that has the specified entity key.

 System::Object ^ GetObjectByKey(System::Data::EntityKey ^ key);
public object GetObjectByKey (System.Data.EntityKey key);
member this.GetObjectByKey : System.Data.EntityKey -> obj
Public Function GetObjectByKey (key As EntityKey) As Object


EntityKey EntityKey EntityKey EntityKey

The key of the object to be found.


An Object that is an instance of an entity type.



This example is based on the AdventureWorks 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())
        // 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 =

        Console.WriteLine("SalesOrderID: {0} Order Number: {1}",
            order.SalesOrderID, order.SalesOrderNumber);
    catch (ObjectNotFoundException ex)
Using context As New AdventureWorksEntities()
        ' Define the entity key values. 
        Dim entityKeyValues As IEnumerable(Of KeyValuePair(Of String, Object)) = _
            New KeyValuePair(Of String, Object)() {New KeyValuePair(Of String, Object)("SalesOrderID", 43680)}

        ' Create the key for a specific SalesOrderHeader object. 
        Dim key As New EntityKey("AdventureWorksEntities.SalesOrderHeaders", entityKeyValues)

        ' Get the object from the context or the persisted store by its key. 
        Dim order As SalesOrderHeader = DirectCast(context.GetObjectByKey(key), SalesOrderHeader)

        Console.WriteLine("SalesOrderID: {0} Order Number: {1}", order.SalesOrderID, order.SalesOrderNumber)
    Catch ex As ObjectNotFoundException
    End Try
End Using


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.

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.

Applies to

See also