How to: Load Paged Results (WCF Data Services)

Important

WCF Data Services has been deprecated and will no longer be available for download from the Microsoft Download Center. WCF Data Services supported earlier versions of the Microsoft OData (V1-V3) protocol only and has not been under active development. OData V1-V3 has been superseded by OData V4, which is an industry standard published by OASIS and ratified by ISO. OData V4 is supported through the OData V4 compliant core libraries available at Microsoft.OData.Core. Support documentation is available at OData.Net, and the OData V4 service libraries are available at Microsoft.AspNetCore.OData.

RESTier is the successor to WCF Data Services. RESTier helps you bootstrap a standardized, queryable, HTTP-based REST interface in minutes. Like WCF Data Services before it, Restier provides simple and straightforward ways to shape queries and intercept submissions before and after they hit the database. And like Web API + OData, you still have the flexibility to add your own custom queries and actions with techniques you're already familiar with.

WCF Data Services enables the data service to limit the number of entities that are returned in a single response feed. When this happens, the final entry in the feed contains a link to the next page of data. The URI for the next page of data is obtained by calling the GetContinuation method of the QueryOperationResponse<T>, which is returned when the DataServiceQuery<TElement> is executed. The URI represented by this object is then used to load the next page of results. For more information, see Loading Deferred Content.

The example in this topic uses the Northwind sample data service and autogenerated client data service classes. This service and the client data classes are created when you complete the WCF Data Services quickstart.

Example

This example uses a do…while loop to load Customers entities from a paged results from the data service.

// 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

Example

This example returns related Orders entities with each Customers entity and uses a do…while loop to load Customers entities pages and a nested while loop to load pages of related Orders entities from the data service.

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

try
{
    // Execute the query for all customers and related orders,
    // and get the response object.
    var response =
        context.Customers.AddQueryOption("$expand", "Orders")
        .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("Customers Page {0}:", ++pageCount);

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

        // Enumerate the customers in the response.
        foreach (Customer c in response)
        {
            Console.WriteLine("\tCustomer Name: {0}", c.CompanyName);
            Console.WriteLine("\tOrders Page {0}:", ++innerPageCount);
            // Get the next link for the collection of related Orders.
            DataServiceQueryContinuation<Order> nextOrdersLink =
                response.GetContinuation(c.Orders);

            while (nextOrdersLink != null)
            {
                foreach (Order o in c.Orders)
                {
                    // Print out the orders.
                    Console.WriteLine("\t\tOrderID: {0} - Freight: ${1}",
                        o.OrderID, o.Freight);
                }

                // Load the next page of Orders.
                var ordersResponse = context.LoadProperty(c, "Orders", nextOrdersLink);
                nextOrdersLink = ordersResponse.GetContinuation();
            }
        }
    }

    // Get the next link, and continue while there is a next link.
    while ((nextLink = 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 nextLink As DataServiceQueryContinuation(Of Customer) = Nothing
Dim pageCount = 0
Dim innerPageCount = 0

Try
    ' Execute the query for all customers and related orders,
    ' and get the response object.
    Dim response = _
    CType(context.Customers.AddQueryOption("$expand", "Orders") _
            .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("Customers Page {0}:", ++pageCount)

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

        ' Enumerate the customers in the response.
        For Each c As Customer In response
            Console.WriteLine(vbTab & "Customer Name: {0}", c.CompanyName)
            Console.WriteLine(vbTab & "Orders Page {0}:", innerPageCount + 1)

            ' Get the next link for the collection of related Orders.
            Dim nextOrdersLink As DataServiceQueryContinuation(Of Order) = _
            response.GetContinuation(c.Orders)

            While nextOrdersLink IsNot Nothing
                For Each o As Order In c.Orders
                    ' Print out the orders.
                    Console.WriteLine(vbTab & vbTab & "OrderID: {0} - Freight: ${1}", _
                            o.OrderID, o.Freight)
                Next
                ' Load the next page of Orders.
                Dim ordersResponse = _
                context.LoadProperty(c, "Orders", nextOrdersLink)
                nextOrdersLink = ordersResponse.GetContinuation()
            End While
        Next
        ' Get the next link, and continue while there is a next link.
        nextLink = response.GetContinuation()
    Loop While nextLink IsNot Nothing
Catch ex As DataServiceQueryException
    Throw New ApplicationException( _
            "An error occurred during query execution.", ex)
End Try

See also