How to: Execute Queries in a Batch (ADO.NET Data Services)

By using the ADO.NET Data Services client library, you can execute more than one query against the data service in a single batch. For more information, see Batching Operations (ADO.NET Data Services).

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 ADO.NET Data Services quickstart.

Example

The following example shows how to call the ExecuteBatch() method to execute an array of DataServiceRequest objects that contains queries that return both Customers and Products objects from the Northwind data service. The collection of QueryOperationResponse objects in the returned DataServiceResponse is enumerated, and the collection of objects contained in each QueryOperationResponse is also enumerated.

Dim customerId = "ALFKI"

' Create the DataServiceContext using the service URI.
Dim context = New NorthwindEntities(svcUri)

' Create the separate query URI's, one that returns 
' a single customer and another that returns all Products.
Dim customerUri = New Uri(svcUri.AbsoluteUri & _
    "/Customers('" & customerId & "')/?$expand=Orders")
Dim productsUri = New Uri(svcUri.AbsoluteUri & _
       "/Products")

' Create the query requests.
Dim customerQuery = New DataServiceRequest(Of Customers)(customerUri)
Dim productsQuery = New DataServiceRequest(Of Products)(productsUri)

' Add the query requests to a batch request array.
Dim batchRequests = _
    New DataServiceRequest() {customerQuery, productsQuery}

Dim batchResponse As DataServiceResponse

Try
    ' Execute the query batch and get the response.
    batchResponse = context.ExecuteBatch(batchRequests)

    If batchResponse.IsBatchResponse Then
        ' Parse the batchResponse.BatchHeaders.
    End If

    ' Enumerate over the results of the query.
    For Each response As QueryOperationResponse In batchResponse
        ' Handle an error response.
        If response.StatusCode > 299 OrElse response.StatusCode < 200 Then
            Console.WriteLine("An error occurred.")
            Console.WriteLine(response.Error.Message)
        Else
            ' Find the response for the Customers query.
            If response.Query.ElementType Is GetType(Customers) Then
                For Each customer As Customers In response
                    Console.WriteLine("Customer: {0}", customer.CompanyName)
                    For Each order As Orders In customer.Orders
                        Console.WriteLine("Order ID: {0} - Freight: {1}", _
                                order.OrderID, order.Freight)
                    Next
                Next
                ' Find the response for the Products query.
            ElseIf response.Query.ElementType Is GetType(Products) Then
                For Each product As Products In response
                    Console.WriteLine("Product: {0}", product.ProductName)
                Next
            End If
        End If
    Next
    ' This type of error is raised when the data service returns with
    ' a response code < 200 or >299 in the top level element.
Catch ex As DataServiceRequestException
    ' Get the response from the exception.
    batchResponse = ex.Response

    If (batchResponse.IsBatchResponse) Then
        ' Parse the batchResponse.BatchHeaders.
    End If
    For Each response As QueryOperationResponse In batchResponse
        If response.Error IsNot Nothing Then
            Console.WriteLine("An error occurred.")
            Console.WriteLine(response.Error.Message)
        End If
    Next
End Try
string customerId = "ALFKI";

// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

// Create the separate query URI's, one that returns 
// a single customer and another that returns all Products.
Uri customerUri = new Uri(svcUri.AbsoluteUri + 
    "/Customers('" + customerId + "')/?$expand=Orders");
Uri productsUri = new Uri(svcUri.AbsoluteUri +
   "/Products");

// Create the query requests.
DataServiceRequest<Customers> customerQuery = 
    new DataServiceRequest<Customers>(customerUri);
DataServiceRequest<Products> productsQuery =
                new DataServiceRequest<Products>(productsUri);

// Add the query requests to a batch request array.
DataServiceRequest[] batchRequests = 
    new DataServiceRequest[]{customerQuery, productsQuery};

DataServiceResponse batchResponse;

try
{
    // Execute the query batch and get the response.
    batchResponse = context.ExecuteBatch(batchRequests);

    if (batchResponse.IsBatchResponse)
    {
        // Parse the batchResponse.BatchHeaders.
    }  
    // Enumerate over the results of the query.
    foreach (QueryOperationResponse response in batchResponse)
    {
        // Handle an error response.
        if (response.StatusCode > 299 || response.StatusCode < 200)
        {
            Console.WriteLine("An error occurred.");
            Console.WriteLine(response.Error.Message);
        }
        else
        {
            // Find the response for the Customers query.
            if (response.Query.ElementType == typeof(Customers))
            {
                foreach (Customers customer in response)
                {
                    Console.WriteLine("Customer: {0}", customer.CompanyName);
                    foreach (Orders order in customer.Orders)
                    {
                        Console.WriteLine("Order ID: {0} - Freight: {1}",
                            order.OrderID, order.Freight);
                    }
                }
            }
            // Find the response for the Products query.
            else if (response.Query.ElementType == typeof(Products))
            {
                foreach (Products product in response)
                {
                    Console.WriteLine("Product: {0}", product.ProductName);
                }
            }
        }
    }
}

// This type of error is raised when the data service returns with
// a response code < 200 or >299 in the top level element.
catch (DataServiceRequestException e)
{
    // Get the response from the exception.
    batchResponse = e.Response;

    if (batchResponse.IsBatchResponse)
    {
        // Parse the batchResponse.BatchHeaders.
    }

    foreach (QueryOperationResponse response in batchResponse)
    {
        if (response.Error != null)
        {
            Console.WriteLine("An error occurred.");
            Console.WriteLine(response.Error.Message);
        }
    }
}

See Also

Other Resources

Using a Data Service in a .NET Framework Application (ADO.NET Data Services)