ObjectContext.TryGetObjectByKey(EntityKey, Object) Metodo

Definizione

Restituisce un oggetto contenente 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.

Restituisce

true se l'oggetto è stato recuperato correttamente. false se key è temporaneo, la connessione è null o 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 contenente l'oggetto EntityKey specificato da ObjectStateManager. Se l'oggetto non è attualmente caricato nel contesto dell'oggetto, viene eseguita una query nel tentativo di restituire l'oggetto dall'origine dati. Per altre informazioni, vedere Query sugli oggetti.

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

Questo metodo restituirà gli oggetti che si trovano nello stato Deleted.

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

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

Si applica a

Vedi anche