ObjectContext.GetObjectByKey(EntityKey) Metodo

Definizione

Restituisce un oggetto con la chiave di entità specificata.

public:
 System::Object ^ GetObjectByKey(System::Data::EntityKey ^ key);
public object GetObjectByKey(System.Data.EntityKey key);
member this.GetObjectByKey : System.Data.EntityKey -> obj
Public Function GetObjectByKey (key As EntityKey) As Object

Parametri

key
EntityKey

Chiave dell'oggetto da trovare.

Valori restituiti

Oggetto Object che è un'istanza di un tipo di entità.

Eccezioni

Il key parametro è null.

L'oggetto non viene trovato nell'oggetto ObjectStateManager o nell'origine dati.

Esempio

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

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    try
    {
        // Define the entity key values.
        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.
        SalesOrderHeader order =
            (SalesOrderHeader)context.GetObjectByKey(key);

        Console.WriteLine("SalesOrderID: {0} Order Number: {1}",
            order.SalesOrderID, order.SalesOrderNumber);
    }
    catch (ObjectNotFoundException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Commenti

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

GetObjectByKey genera un oggetto ObjectNotFoundException quando non è possibile trovare l'oggetto . Per evitare di gestire questa eccezione, usare invece il TryGetObjectByKey metodo .

Questo metodo restituirà oggetti nello Deleted stato .

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

Si applica a

Vedi anche