Как определить количество сущностей, возвращенных запросом (службы WCF Data Services)

В Службы WCF Data Services можно определить число сущностей в наборе сущностей, заданном в URI запроса. Это число можно включить в результат запроса или представить как целое значение. Дополнительные сведения см. в разделе Запросы к службе данных (службы WCF Data Services).

Пример в этом разделе использует образец службы данных Northwind и автоматически сформированные клиентские классы службы данных. Эта служба и клиентские классы данных создаются после выполнения действий, описанных в разделе Краткое руководство по службам WCF Data Services.

Пример

В этом примере запрос выполняется после вызова метода IncludeTotalCount. Свойство TotalCount возвращает число сущностей в наборе сущностей Customers.

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

' Define a new query for Customers that includes the total count.
Dim query As DataServiceQuery(Of Customer) = _
context.Customers.IncludeTotalCount()

Try
    ' Execute the query for all customers and get the response object.
    Dim response As QueryOperationResponse(Of Customer) = _
        CType(query.Execute(), QueryOperationResponse(Of 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.
    For Each customer As Customer In response
        Console.WriteLine("\tCustomer Name: {0}", customer.CompanyName)
    Next
Catch ex As DataServiceQueryException
    Throw New ApplicationException( _
            "An error occurred during query execution.", ex)
End Try
// 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);
}

В данном примере метод Count вызывается для возвращения только целого значения числа сущностей в наборе сущностей Customers.

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

' Define a new query for Customers.
Dim query As DataServiceQuery(Of Customer) = context.Customers

Try
    ' Execute the query to just return the value of all customers in the set.
    Dim totalCount = query.Count()

    ' Retrieve the total count from the response.
    Console.WriteLine("There are {0} customers in total.", totalCount)
Catch ex As DataServiceQueryException
    Throw New ApplicationException( _
            "An error occurred during query execution.", ex)
End Try
// 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);
}

См. также

Основные понятия

Запросы к службе данных (службы WCF Data Services)