This topic has not yet been rated - Rate this topic

How to: Determine the Number of Entities Returned by a Query (WCF Data Services)

With WCF Data Services, you can determine the number of entities that are in the entity set specified by a query URI. This count can be included either along with the query result or as an integer value. For more information, see Querying the Data Service (WCF 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 WCF Data Services quickstart.

This example executes a query after calling the IncludeTotalCount method. The TotalCount property returns the number of entities in the Customers entity set.

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

// Define a new query for Customers that includes the total count.
DataServiceQuery<Customer> query = context.Customers.IncludeTotalCount();

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

    // Retrieve the total count from the response.
    Console.WriteLine("There are a total of {0} customers.", response.TotalCount);

    // Enumerate the customers in the response. 
    foreach (Customer customer in response)
    {
        Console.WriteLine("\tCustomer Name: {0}", customer.CompanyName);
    }
}
catch (DataServiceQueryException ex)
{
    throw new ApplicationException(
        "An error occurred during query execution.", ex);
}

This example calls the Count method to return only an integer value that is the number of entities in the Customers entity set.

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

// Define a new query for Customers.
DataServiceQuery<Customer> query = context.Customers;

try
{    
    // Execute the query to just return the value of all customers in the set. 
    int totalCount = query.Count();

    // Retrieve the total count from the response.
    Console.WriteLine("There are {0} customers in total.", totalCount);
}
catch (DataServiceQueryException ex)
{
    throw new ApplicationException(
        "An error occurred during query execution.", ex);
}
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.