Язык

DataServiceContext.Execute Метод

Определение

Отправляет запрос в службу данных для выполнения определенного URI.

Перегрузки

Имя Описание
Execute<T>(DataServiceQueryContinuation<T>)

Отправляет запрос в службу данных, чтобы получить следующую страницу данных в результате запроса на страницу.

Execute<TElement>(Uri)

Отправляет запрос в службу данных для выполнения определенного URI.

Execute<T>(DataServiceQueryContinuation<T>)

Отправляет запрос в службу данных, чтобы получить следующую страницу данных в результате запроса на страницу.

public:
generic <typename T>
 System::Data::Services::Client::QueryOperationResponse<T> ^ Execute(System::Data::Services::Client::DataServiceQueryContinuation<T> ^ continuation);
public System.Data.Services.Client.QueryOperationResponse<T> Execute<T>(System.Data.Services.Client.DataServiceQueryContinuation<T> continuation);
member this.Execute : System.Data.Services.Client.DataServiceQueryContinuation<'T> -> System.Data.Services.Client.QueryOperationResponse<'T>
Public Function Execute(Of T) (continuation As DataServiceQueryContinuation(Of T)) As QueryOperationResponse(Of T)

Параметры типа

T

Тип, возвращаемый запросом.

Параметры

continuation
DataServiceQueryContinuation<T>

DataServiceQueryContinuation<T> Объект, представляющий следующую страницу данных для возврата из службы данных.

Возвращаемое значение

Ответ, содержащий следующую страницу данных в результате запроса.

Исключения

При возникновении ошибки во время выполнения запроса или при преобразовании содержимого сообщения ответа в объекты.

Комментарии

Предоставленный DataServiceQueryContinuation<T> объект содержит универсальный код ресурса (URI), который при выполнении возвращает следующую страницу данных в результате запроса.

Применяется к

Execute<TElement>(Uri)

Отправляет запрос в службу данных для выполнения определенного URI.

public:
generic <typename TElement>
 System::Collections::Generic::IEnumerable<TElement> ^ Execute(Uri ^ requestUri);
public System.Collections.Generic.IEnumerable<TElement> Execute<TElement>(Uri requestUri);
member this.Execute : Uri -> seq<'Element>
Public Function Execute(Of TElement) (requestUri As Uri) As IEnumerable(Of TElement)

Параметры типа

TElement

Тип, который возвращает запрос.

Параметры

requestUri
Uri

Универсальный код ресурса (URI), в который будет отправлен запрос. URI может быть любым допустимым URI службы данных. Может содержать параметры запроса $.

Возвращаемое значение

IEnumerable<TElement>

Результаты операции запроса.

Исключения

Если ответ не получен из запроса на запрос requestUri.

Когда requestUri есть null.

Если requestUri недопустимый универсальный код ресурса (URI) для службы данных.

При возникновении ошибки во время выполнения запроса или при преобразовании содержимого сообщения ответа в объекты.

Служба данных возвращает ошибку HTTP 404: ошибка ресурса не найдена.

Примеры

В этом примере используется do…while цикл для загрузки Customers сущностей из страничных результатов из службы данных. Метод Execute вызывается с помощью URI следующей ссылки для получения следующей страницы данных.

// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);
DataServiceQueryContinuation<Customer> token = null;
int pageCount = 0;

try
{
    // Execute the query for all customers and get the response object.
    QueryOperationResponse<Customer> response =
        context.Customers.Execute() as QueryOperationResponse<Customer>;

    // With a paged response from the service, use a do...while loop
    // to enumerate the results before getting the next link.
    do
    {
        // Write the page number.
        Console.WriteLine("Page {0}:", pageCount++);

        // If nextLink is not null, then there is a new page to load.
        if (token != null)
        {
            // Load the new page from the next link URI.
            response = context.Execute<Customer>(token)
                as QueryOperationResponse<Customer>;
        }

        // Enumerate the customers in the response.
        foreach (Customer customer in response)
        {
            Console.WriteLine("\tCustomer Name: {0}", customer.CompanyName);
        }
    }

    // Get the next link, and continue while there is a next link.
    while ((token = response.GetContinuation()) != null);
}
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)
Dim token As DataServiceQueryContinuation(Of Customer) = Nothing
Dim pageCount = 0

Try
    ' Execute the query for all customers and get the response object.
    Dim response As QueryOperationResponse(Of Customer) =
        CType(context.Customers.Execute(), QueryOperationResponse(Of Customer))

    ' With a paged response from the service, use a do...while loop 
    ' to enumerate the results before getting the next link.
    Do
        ' Write the page number.
        Console.WriteLine("Page {0}:", pageCount + 1)

        ' If nextLink is not null, then there is a new page to load.
        If token IsNot Nothing Then
            ' Load the new page from the next link URI.
            response = CType(context.Execute(Of Customer)(token),
            QueryOperationResponse(Of Customer))
        End If

        ' Enumerate the customers in the response.
        For Each customer As Customer In response
            Console.WriteLine(vbTab & "Customer Name: {0}", customer.CompanyName)
        Next

        ' Get the next link, and continue while there is a next link.
        token = response.GetContinuation()
    Loop While token IsNot Nothing
Catch ex As DataServiceQueryException
    Throw New ApplicationException(
            "An error occurred during query execution.", ex)
End Try

Комментарии

Метод Execute используется для запроса службы данных по URI; метод вызывает выдачу HTTP-запроса GET в службу данных. Указанный URI запроса может быть абсолютным или относительным.

Если этот requestUri метод является абсолютным, этот метод проверяет, указывает ли URI на ту же службу данных, которая была указана при создании DataServiceContext. Если этот requestUri метод является относительным, этот метод удаляет любые ведущие косые черты и добавляет requestUri к тому, что было предоставлено при создании DataServiceContext. Косая черта добавляется после того, как URI передается конструктору DataServiceContext , если он еще не присутствует.

Когда этот метод возвращается, все HTTP-ответы для запроса считываются из сетевого потока, но ответ не будет обработан; Нет разрешения удостоверений или материализации объектов. Разрешение удостоверений и полная материализация объектов не происходят для указанной сущности в ответе, пока она не будет перечислена.

См. также раздел

Применяется к