ObjectContext.GetObjectByKey(EntityKey) Método

Definição

Retorna um objeto que tem a chave de entidade especificada.

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

Parâmetros

key
EntityKey

A chave do objeto a ser encontrado.

Retornos

Uma Object instância de um tipo de entidade.

Exceções

O key parâmetro é null.

O objeto não é encontrado na ObjectStateManager fonte de dados ou na fonte de dados.

Exemplos

Este exemplo cria uma EntityKey entidade do tipo determinado e, em seguida, busca uma entidade por chave.

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());
    }
}

Comentários

GetObjectByKey tenta recuperar um objeto que tem o especificado EntityKey do ObjectStateManager. Se o objeto não estiver carregado no contexto do objeto, uma consulta será executada na tentativa de retornar o objeto da fonte de dados.

GetObjectByKey gera um ObjectNotFoundException quando o objeto não pode ser encontrado. Para evitar lidar com essa exceção, use o TryGetObjectByKey método.

Esse método retornará objetos no Deleted estado.

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

Aplica-se a

Confira também