Export (0) Print
Expand All
Expand Minimize

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 (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

Community Additions

ADD
Show:
© 2015 Microsoft