ObjectContext.TryGetObjectByKey(EntityKey, Object) Metodo

Definizione

Restituisce un oggetto con la chiave di entità specificata.

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

Parametri

key
EntityKey

Chiave dell'oggetto da trovare.

value
Object

Quando termina, questo metodo contiene l'oggetto .

Valori restituiti

true se l'oggetto è stato recuperato correttamente. false key se è temporaneo, la connessione è nullo value è null.

Eccezioni

Metadati incompatibili per key.

key è null.

Esempio

Questo esempio crea un oggetto per un'entità EntityKey del tipo specificato e quindi tenta di recuperare un'entità in base alla chiave.

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.");
    }
}

Commenti

TryGetObjectByKey tenta di recuperare un oggetto con l'oggetto specificato EntityKey dall'oggetto ObjectStateManager. Se l'oggetto non è attualmente caricato nel contesto dell'oggetto, viene eseguita una query nel tentativo di restituire l'oggetto dall'origine dati.

Utilizzare il TryGetObjectByKey metodo per evitare di gestire l'oggetto ObjectNotFoundException generato da GetObjectByKey quando non è possibile trovare l'oggetto.

Questo metodo restituirà oggetti nello Deleted stato .

Non è possibile utilizzare una chiave temporanea per restituire un oggetto dall'origine dati.

Il metodo TryGetObjectByKey applica lo schema standard .NET TryParse per il metodo GetObjectByKey, restituendo false quando viene intercettata la ObjectNotFoundException.

Si applica a

Vedi anche