ObjectContext.TryGetObjectByKey(EntityKey, Object) Método

Definição

Devolve um objeto que tem a chave de entidade especificada.

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

Parâmetros

key
EntityKey

A chave do objeto a encontrar.

value
Object

Quando este método retorna, contém o objeto.

Devoluções

true se o objeto fosse recuperado com sucesso. false Se o key for temporário, a ligação é null, ou o value é null.

Exceções

Metadados incompatíveis para key.

key é null.

Exemplos

Este exemplo cria um EntityKey para uma entidade do tipo dado e depois tenta recuperar uma entidade por chave.

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

Observações

TryGetObjectByKey tenta recuperar um objeto que tenha o especificado EntityKey a partir do ObjectStateManager. Se o objeto não estiver atualmente carregado no contexto do objeto, é executada uma consulta numa tentativa de devolver o objeto da fonte de dados. Para obter mais informações, consulte Consultas de Objetos.

Use o TryGetObjectByKey método para evitar manipular o ObjectNotFoundException levantamento quando GetObjectByKey o objeto não puder ser encontrado.

Este método devolverá objetos no Deleted estado.

Uma chave temporária não pode ser usada para devolver um objeto da fonte de dados.

O método TryGetObjectByKey aplica o padrão .NET TryParse para o método GetObjectByKey, retornando false quando o ObjectNotFoundException é apanhado.

Aplica-se a

Ver também