ObjectContext::TryGetObjectByKey Method (EntityKey^, Object^%)


Returns an object that has the specified entity key.

Namespace:   System.Data.Objects
Assembly:  System.Data.Entity (in System.Data.Entity.dll)

bool TryGetObjectByKey(
	EntityKey^ key,
	[OutAttribute] Object^% value


Type: System.Data::EntityKey^

The key of the object to be found.

Type: System::Object^%

When this method returns, contains the object.

Return Value

Type: System::Boolean

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

Exception Condition

Incompatible metadata for key.


key is null.

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 M:System.Data.Objects.ObjectContext.TryGetObjectByKey(System.Data.EntityKey,System.Object) method applies the standard .NET TryParse pattern for the GetObjectByKey method, returning false when the ObjectNotFoundException is caught.

The example in this topic is based on the AdventureWorks Sales Model. The example creates an EntityKey for an entity of the given type and then tries to retrieve an entity by key.

No code example is currently available or this language may not be supported.

.NET Framework
Available since 3.5
Return to top