Export (0) Print
Expand All

ObjectContext.TryGetObjectByKey Method

Returns an object that has the specified entity key.

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

'Declaration
Public Function TryGetObjectByKey ( _
	key As EntityKey, _
	<OutAttribute> ByRef value As Object _
) As Boolean

Parameters

key
Type: System.Data.EntityKey
The key of the object to be found.
value
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 Nothing, or the value is Nothing.

ExceptionCondition
ArgumentException

Incompatible metadata for key.

ArgumentNullException

key is Nothing.

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 (Entity Framework).

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(EntityKey, 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 Adventure Works Sales Model. The example creates an EntityKey for an entity of the given type and then tries to retrieve an entity by key.


Using context As New AdventureWorksEntities()
    Dim entity As Object = Nothing
    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. 
    If context.TryGetObjectByKey(key, entity) Then
        Console.WriteLine("The requested " & entity.GetType().FullName & " object was found")
    Else
        Console.WriteLine("An object with this key could not be found.")
    End If
End Using


.NET Framework

Supported in: 4, 3.5 SP1

.NET Framework Client Profile

Supported in: 4

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Community Additions

ADD
Show:
© 2014 Microsoft