Editare

Partajați prin


ObjectContext.TryGetObjectByKey(EntityKey, Object) Method

Definition

Returns an object that has the specified entity key.

public:
 bool TryGetObjectByKey(System::Data::EntityKey ^ key, [Runtime::InteropServices::Out] System::Object ^ % value);
public bool TryGetObjectByKey (System.Data.EntityKey key, out object value);
member this.TryGetObjectByKey : System.Data.EntityKey * obj -> bool
Public Function TryGetObjectByKey (key As EntityKey, ByRef value As Object) As Boolean

Parameters

key
EntityKey

The key of the object to be found.

value
Object

When this method returns, contains the object.

Returns

true if the object was retrieved successfully. false if the key is temporary, the connection is null, or the value is null.

Exceptions

Incompatible metadata for key.

key is null.

Examples

This example creates an EntityKey for an entity of the given type and then tries to retrieve an entity by key.

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    Object entity = null;
    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.
    if (context.TryGetObjectByKey(key, out entity))
    {
        Console.WriteLine("The requested " + entity.GetType().FullName +
            " object was found");
    }
    else
    {
        Console.WriteLine("An object with this key " +
            "could not be found.");
    }
}

Remarks

TryGetObjectByKey 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.

Use the TryGetObjectByKey method to avoid handling the ObjectNotFoundException raised by GetObjectByKey when the object cannot be found.

This method will return objects in the Deleted state.

A temporary key cannot be used to return an object from the data source.

The TryGetObjectByKey method applies the standard .NET TryParse pattern for the GetObjectByKey method, returning false when the ObjectNotFoundException is caught.

Applies to

See also