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

Note Note

This topic describes new functionality in ADO.NET Data Services that is available as an update to the .NET Framework version 3.5 Service Pack 1. You can download and install the update from the Microsoft Download Center.

With ADO.NET 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 (IncludeTotalCount()) or as an integer valued result (Count``1(IEnumerable<UMP>)). For more information, see Querying the Data Service (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.

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<Customers> query = context.Customers.IncludeTotalCount();

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

    // 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 (Customers customer in response)
    {
        Console.WriteLine("\tCustomer Name: {0}", customer.CompanyName);
    }
}
catch (Exception ex)
{
    throw new ApplicationException(
        "An error occurred during query execution.", ex);
}


This example calls the Count``1(IEnumerable<UMP>) 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<Customers> 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 (Exception ex)
{
    throw new ApplicationException(
        "An error occurred during query execution.", ex);
}


Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2015 Microsoft