How to: Return a Specific Object Using its Key

This topic shows how to retrieve an entity by its key values instead of explicitly creating and executing an object query. The examples in this topic are based on the AdventureWorks Sales Model. To run the code in these examples, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define the Model and Mapping Files. You can also use the Entity Data Model Wizard to define the AdventureWorks Sales Model. For more information, see How to: Use the Entity Data Model Wizard.

Example

This example uses the GetObjectByKey method on ObjectContext to return an object with the specified EntityKey into the object context. This example handles the ObjectNotFoundException that occurs when the supplied EntityKey does not correspond to an existing entity. To avoid the ObjectNotFoundException, call TryGetObjectByKey, which returns false instead of raising an exception.

Using context As New AdventureWorksEntities()
    Try
        ' 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
        Console.WriteLine(ex.ToString())
    End Try
End Using
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());
    }
}

See Also

Tasks

How to: Execute a Query that Returns Entity Type Objects
How to: Use Query Paths to Shape Results

Concepts

Querying a Conceptual Model