DataServiceContext Classe
Definição
O DataServiceContext representa o contexto do runtime do serviço de dados.The DataServiceContext represents the runtime context of the data service.
public ref class DataServiceContext
public class DataServiceContext
type DataServiceContext = class
Public Class DataServiceContext
- Herança
-
DataServiceContext
Exemplos
O exemplo a seguir mostra como usar o DataServiceContext gerado pela ferramenta de Adicionar referência de serviço para executar implicitamente uma consulta no serviço de dados Northwind que retorna todos os clientes.The following example shows how to use the DataServiceContext generated by the Add Service Reference tool to implicitly execute a query against the Northwind data service that returns all customers. O URI do conjunto de entidades de Customers é determinado automaticamente pelo contexto.The URI of the requested Customers entity set is determined automatically by the context. A consulta é executada implicitamente quando a enumeração ocorre.The query is executed implicitly when the enumeration occurs. O serviço de dados Northwind é criado quando você conclui o WCF Data Services.The Northwind data service is created when you complete the WCF Data Services .
// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);
// Define a new query for Customers.
DataServiceQuery<Customer> query = context.Customers;
try
{
// Enumerate over the query result, which is executed implicitly.
foreach (Customer customer in query)
{
Console.WriteLine("Customer Name: {0}", customer.CompanyName);
}
}
catch (DataServiceQueryException ex)
{
throw new ApplicationException(
"An error occurred during query execution.", ex);
}
' Create the DataServiceContext using the service URI.
Dim context = New NorthwindEntities(svcUri)
' Define a new query for Customers.
Dim query As DataServiceQuery(Of Customer) = context.Customers
Try
' Enumerate over the query result, which is executed implicitly.
For Each customer As Customer In query
Console.WriteLine("Customer Name: {0}", customer.CompanyName)
Next
Catch ex As DataServiceQueryException
Throw New ApplicationException( _
"An error occurred during query execution.", ex)
End Try
Comentários
WCF Data Services são sem monitoração de estado, mas o DataServiceContext não é.WCF Data Services are stateless, but the DataServiceContext is not. O estado no cliente é mantido entre as interações para dar suporte a recursos como o gerenciamento de atualizações.State on the client is maintained between interactions in order to support features such as update management. Essa classe, e a DataServiceQuery classe que representa uma solicitação HTTP específica para um serviço de dados, são as duas classes principais na biblioteca de cliente.This class, and the DataServiceQuery class that represents a particular HTTP request to a data service, are the two main classes in the client library.
Construtores
| DataServiceContext(Uri) |
Inicializa uma nova instância da classe DataServiceContext com o |
Propriedades
| ApplyingChanges |
Obtém um valor que indica se o DataServiceContext está atualmente aplicando as alterações aos objetos controlados.Gets a value that indicates whether the DataServiceContext is currently applying changes to tracked objects. |
| BaseUri |
Obtém o URI absoluto identificando a raiz do serviço de dados de destino.Gets the absolute URI identifying the root of the target data service. |
| Credentials |
Obtém ou define as informações de autenticação usadas por cada consulta criada com o objeto DataServiceContext.Gets or sets the authentication information that is used by each query created by using the DataServiceContext object. |
| DataNamespace |
Obtém ou define o namespace de XML para itens de dados, não itens de metadados, de uma carga de Atom.Gets or sets the XML namespace for data items, not metadata items, of an Atom payload. |
| Entities |
Obtém uma lista de todos os recursos atualmente acompanhados pelo DataServiceContext.Gets a list of all the resources currently being tracked by the DataServiceContext. |
| IgnoreMissingProperties |
Obtém ou define se as propriedades lidas do tipo devem ser mapeadas para propriedades no tipo do lado do cliente.Gets or sets whether the properties read from the type must be mapped to properties on the client-side type. |
| IgnoreResourceNotFoundException |
Obtém ou define se uma exceção é acionada quando um erro 404 (recurso não encontrado) é retornado pelo serviço de dados.Gets or sets whether an exception is raised when a 404 error (resource not found) is returned by the data service. |
| Links |
Obtém a coleção de todas as associações ou links que estão sendo atualmente controlados pelo objeto DataServiceContext.Gets the collection of all associations or links currently being tracked by the DataServiceContext object. |
| MergeOption |
Obtém ou define a opção de sincronização para o recebimento de entidades de um serviço de dados.Gets or sets the synchronization option for receiving entities from a data service. |
| ResolveName |
Obtém ou define uma função para substituir a estratégia de resolução de tipo padrão usada pela biblioteca de cliente durante o envio de entidades para um serviço de dados.Gets or sets a function to override the default type resolution strategy used by the client library when you send entities to a data service. |
| ResolveType |
Obtém ou define uma função que é usada para substituir a opção de resolução de tipo padrão usada pela biblioteca de cliente durante o recebimento de entidades de um serviço de dados.Gets or sets a function that is used to override the default type resolution option that is used by the client library when receiving entities from a data service. |
| SaveChangesDefaultOptions |
Obtém ou define os valores SaveChangesOptions usados pelo método SaveChanges().Gets or sets the SaveChangesOptions values that are used by the SaveChanges() method. |
| Timeout |
Obtém ou define a opção de tempo limite usada para a solicitação HTTP subjacente para o serviço de dados.Gets or sets the time-out option that is used for the underlying HTTP request to the data service. |
| TypeScheme |
Obtém ou define o URI usado para indicar qual esquema de tipo é usado pelo serviço.Gets or sets the URI used to indicate what type scheme is used by the service. |
| UsePostTunneling |
Obtém ou define um valor booliano que indica se o túnel de postagem deve ser usado.Gets or sets a Boolean value that indicates whether to use post tunneling. |
Métodos
| AddLink(Object, String, Object) |
Adiciona o link especificado ao conjunto de objetos que DataServiceContext está acompanhando.Adds the specified link to the set of objects the DataServiceContext is tracking. |
| AddObject(String, Object) |
Adiciona o objeto especificado ao conjunto de objetos que DataServiceContext está acompanhando.Adds the specified object to the set of objects that the DataServiceContext is tracking. |
| AddRelatedObject(Object, String, Object) |
Adiciona um objeto relacionado ao contexto e cria o link que define a relação entre os dois objetos em uma única solicitação.Adds a related object to the context and creates the link that defines the relationship between the two objects in a single request. |
| AttachLink(Object, String, Object) |
Notifica o DataServiceContext para começar a acompanhar o link especificado que define uma relação entre objetos de entidade.Notifies the DataServiceContext to start tracking the specified link that defines a relationship between entity objects. |
| AttachTo(String, Object) |
Notifica o DataServiceContext para iniciar o acompanhamento do recurso especificado e fornece o local do recurso no conjunto de recursos especificado.Notifies the DataServiceContext to start tracking the specified resource and supplies the location of the resource within the specified resource set. |
| AttachTo(String, Object, String) |
Notifica o DataServiceContext para iniciar o acompanhamento do recurso especificado e fornece o local do recurso no conjunto de recursos especificado.Notifies the DataServiceContext to start tracking the specified resource and supplies the location of the resource in the specified resource set. |
| BeginExecute<T>(DataServiceQueryContinuation<T>, AsyncCallback, Object) |
Envia de forma assíncrona uma solicitação ao serviço de dados para recuperar a próxima página de dados em um resultado paginado da consulta.Asynchronously sends a request to the data service to retrieve the next page of data in a paged query result. |
| BeginExecute<TElement>(Uri, AsyncCallback, Object) |
Envia de forma assíncrona a solicitação, para que essa chamada não bloqueie o processamento enquanto aguarda os resultados do serviço.Asynchronously sends the request so that this call does not block processing while waiting for the results from the service. |
| BeginExecuteBatch(AsyncCallback, Object, DataServiceRequest[]) |
Envia de forma assíncrona um grupo de consultas como um lote para o serviço de dados.Asynchronously submits a group of queries as a batch to the data service. |
| BeginGetReadStream(Object, DataServiceRequestArgs, AsyncCallback, Object) |
Obtém de forma assíncrona os dados da propriedade binária para a entidade especificada como um fluxo de dados junto com os cabeçalhos da mensagem especificada.Asynchronously gets binary property data for the specified entity as a data stream along with the specified message headers. |
| BeginLoadProperty(Object, String, AsyncCallback, Object) |
Carrega de forma assíncrona o valor da propriedade especificada do serviço de dados.Asynchronously loads the value of the specified property from the data service. |
| BeginLoadProperty(Object, String, DataServiceQueryContinuation, AsyncCallback, Object) |
Carrega de forma assíncrona a próxima página de entidades relacionadas do serviço de dados usando o objeto de continuação de consulta fornecido.Asynchronously loads the next page of related entities from the data service by using the supplied query continuation object. |
| BeginLoadProperty(Object, String, Uri, AsyncCallback, Object) |
Carrega de forma assíncrona uma página de entidades relacionadas do serviço de dados usando o próximo URI de link fornecido.Asynchronously loads a page of related entities from the data service by using the supplied next link URI. |
| BeginSaveChanges(AsyncCallback, Object) |
Envia de forma assíncrona as alterações pendentes ao serviço de dados coletadas pelo DataServiceContext, desde as últimas alterações salvas.Asynchronously submits the pending changes to the data service collected by the DataServiceContext since the last time changes were saved. |
| BeginSaveChanges(SaveChangesOptions, AsyncCallback, Object) |
Envia de forma assíncrona as alterações pendentes ao serviço de dados coletadas pelo DataServiceContext, desde as últimas alterações salvas.Asynchronously submits the pending changes to the data service collected by the DataServiceContext since the last time changes were saved. |
| CancelRequest(IAsyncResult) |
Tenta cancelar a operação associada ao objeto IAsyncResult fornecido.Attempts to cancel the operation that is associated with the supplied IAsyncResult object. |
| CreateQuery<T>(String) |
Cria uma consulta do serviço de dados para dados de um tipo genérico especificado.Creates a data service query for data of a specified generic type. |
| DeleteLink(Object, String, Object) |
Altera o estado do link para excluído na lista de links acompanhados pelo DataServiceContext.Changes the state of the link to deleted in the list of links being tracked by the DataServiceContext. |
| DeleteObject(Object) |
Altera o estado do objeto especificado a ser excluído no DataServiceContext.Changes the state of the specified object to be deleted in the DataServiceContext. |
| Detach(Object) |
Remove a entidade da lista de entidades que o DataServiceContext está acompanhando.Removes the entity from the list of entities that the DataServiceContext is tracking. |
| DetachLink(Object, String, Object) |
Remove o link especificado na lista de links que estão sendo acompanhados pelo DataServiceContext.Removes the specified link from the list of links being tracked by the DataServiceContext. |
| EndExecute<TElement>(IAsyncResult) |
Chamado para concluir o BeginExecute<TElement>(Uri, AsyncCallback, Object).Called to complete the BeginExecute<TElement>(Uri, AsyncCallback, Object). |
| EndExecuteBatch(IAsyncResult) |
Chamado para concluir o BeginExecuteBatch(AsyncCallback, Object, DataServiceRequest[]).Called to complete the BeginExecuteBatch(AsyncCallback, Object, DataServiceRequest[]). |
| EndGetReadStream(IAsyncResult) |
Chamado para concluir a operação assíncrona de recuperação de uma propriedade binária como um fluxo.Called to complete the asynchronous operation of retrieving a binary property as a stream. |
| EndLoadProperty(IAsyncResult) |
Chamado para concluir a operação BeginLoadProperty(Object, String, AsyncCallback, Object).Called to complete the BeginLoadProperty(Object, String, AsyncCallback, Object) operation. |
| EndSaveChanges(IAsyncResult) |
Chamado para concluir a operação BeginSaveChanges(AsyncCallback, Object).Called to complete the BeginSaveChanges(AsyncCallback, Object) operation. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| Execute<T>(DataServiceQueryContinuation<T>) |
Envia uma solicitação ao serviço de dados para recuperar a próxima página de dados em um resultado paginado da consulta.Sends a request to the data service to retrieve the next page of data in a paged query result. |
| Execute<TElement>(Uri) |
Envia uma solicitação ao serviço de dados para executar um URI específico.Sends a request to the data service to execute a specific URI. |
| ExecuteBatch(DataServiceRequest[]) |
Envia um grupo de consultas como um lote para o serviço de dados.Submits a group of queries as a batch to the data service. |
| GetEntityDescriptor(Object) |
Obtém o EntityDescriptor para o objeto de entidade fornecido.Gets the EntityDescriptor for the supplied entity object. |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetLinkDescriptor(Object, String, Object) |
Obtém o LinkDescriptor para um link específico que define a relação entre duas entidades.Gets the LinkDescriptor for a specific link that defines the relationship between two entities. |
| GetMetadataUri() |
Obtém um URI do local dos metadados .edmx.Gets a URI of the location of .edmx metadata. |
| GetReadStream(Object) |
Obtém dados de propriedade binária para a entidade especificada como um fluxo de dados.Gets binary property data for the specified entity as a data stream. |
| GetReadStream(Object, DataServiceRequestArgs) |
Obtém os dados de propriedade binária para a entidade especificada como um fluxo de dados junto com os cabeçalhos da mensagem especificada.Gets binary property data for the specified entity as a data stream along with the specified message headers. |
| GetReadStream(Object, String) |
Obtém os dados de propriedade binária para a entidade especificada como um fluxo de dados, com o cabeçalho da mensagem Accept.Gets binary property data for the specified entity as a data stream, with the specified Accept message header. |
| GetReadStreamUri(Object) |
Obtém o URI usado para retornar dados de propriedade binária como um fluxo de dados.Gets the URI that is used to return binary property data as a data stream. |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| LoadProperty(Object, String) |
Carrega o conteúdo adiado para uma propriedade especificada do serviço de dados.Loads deferred content for a specified property from the data service. |
| LoadProperty(Object, String, DataServiceQueryContinuation) |
Carrega a próxima página de entidades relacionadas do serviço de dados usando o objeto de continuação de consulta fornecido.Loads the next page of related entities from the data service by using the supplied query continuation object. |
| LoadProperty(Object, String, Uri) |
Carrega uma página de entidades relacionadas usando o próximo URI de link fornecido.Loads a page of related entities by using the supplied next link URI. |
| LoadProperty<T>(Object, String, DataServiceQueryContinuation<T>) |
Carrega a próxima página de entidades relacionadas do serviço de dados usando o objeto de continuação de consulta genérico fornecido.Loads the next page of related entities from the data service by using the supplied generic query continuation object. |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| SaveChanges() |
Salva as alterações que o DataServiceContext está acompanhamento para o armazenamento.Saves the changes that the DataServiceContext is tracking to storage. |
| SaveChanges(SaveChangesOptions) |
Salva as alterações que o DataServiceContext está acompanhamento para o armazenamento.Saves the changes that the DataServiceContext is tracking to storage. |
| SetLink(Object, String, Object) |
Notifica o DataServiceContext que existe um novo link entre os objetos especificados e que o link é representado pela propriedade especificada pelo parâmetro |
| SetSaveStream(Object, Stream, Boolean, DataServiceRequestArgs) |
Define um novo fluxo de dados como a propriedade binária de uma entidade, com as configurações especificadas na mensagem de solicitação.Sets a new data stream as the binary property of an entity, with the specified settings in the request message. |
| SetSaveStream(Object, Stream, Boolean, String, String) |
Define um novo fluxo de dados como a propriedade binária de uma entidade.Sets a new data stream as the binary property of an entity. Os cabeçalhos Content-Type e Slug especificados são incluídos na mensagem de solicitação.The specified Content-Type and Slug headers are included in the request message. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
| TryGetEntity<TEntity>(Uri, TEntity) |
Testa a recuperação de uma entidade que está sendo acompanhada pelo DataServiceContext por referência ao URI da entidade.Test retrieval of an entity being tracked by the DataServiceContext by reference to the URI of the entity. |
| TryGetUri(Object, Uri) |
Recupera o URI canônico associado à entidade especificada, se disponível.Retrieves the canonical URI associated with the specified entity, if available. |
| UpdateObject(Object) |
Altera o estado do objeto especificado no DataServiceContext para Modified.Changes the state of the specified object in the DataServiceContext to Modified. |
Eventos
| ReadingEntity |
Ocorre depois que os dados de entidade foram lidos por completo no objeto de entidade.Occurs after entity data has been completely read into the entity object. |
| SendingRequest |
Ocorre quando um novo HttpWebRequest foi criado.Occurs when a new HttpWebRequest has been created. |
| WritingEntity |
Ocorre depois que uma entidade foi totalmente serializada em XML em uma mensagem de solicitação.Occurs after an entity has been fully serialized into XML in a request message. |