How to: Return a Specific Object Using its Key (Entity Framework)

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 (EDM). 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 an Entity Data Model (Entity Framework). 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 (Entity Framework).

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 (AdventureWorksEntities advWorksContext =
    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.SalesOrderHeader", entityKeyValues);

        // Get the object from the context or the persisted store by its key.
        SalesOrderHeader order =
            (SalesOrderHeader)advWorksContext.GetObjectByKey(key);

        Console.WriteLine("SalesOrderID: {0} Order Number: {1}",
            order.SalesOrderID, order.SalesOrderNumber);
    }
    catch (ObjectNotFoundException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

See Also

Show: