Part 14d – OData v4 in ASP.NET WebApi – Query Options – COUNT

This is a series of blogs detailing my introduction to using OData v4 with C# and ASP.NET WebApi.

The source code for the project can be found here.

Up to now we have been creating individual controller actions for our entities either for selecting all entities or selecting entities by key. One of the powers of OData is the query like syntax we can apply within the Url which does not need additional controller actions. In this blog we will look at the COUNT query option.

Creating the Project

The Project is called Part14.

Query All Employees

Following on from the last blog. We can view all Employees as follows.

From Postman issue a GET request with http://localhost:40000/OData/Employees.

Get a Count of the Number of Employees

Before we issue the query we need to enable the count option in our model. This is the same as what we did for select and in fact, what we need to do for all query options.

private static IEdmModel GetEdmModel()
   ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

      .Filter(QueryOptionSetting.Disabled, "City")
      .Select(SelectExpandType.Disabled, "Notes");

   builder.EntityType<Employee>().Ignore(p => p.Photo);
   builder.EntityType<Employee>().Ignore(p => p.PhotoPath);


   return builder.GetEdmModel();

From Postman issue a GET request with http://localhost:40000/odata/Employees/$count

Notice we just get a numeric value back which indicates 9 employees were returned. The result is not in a JSON format.

If we look at the backend query we can see the query does a count but not in the typical way.

Get a Count of the Number of Employees from Region WA

We cannot just put count anywhere. On a filter for example, it must go first.

From Postman issue a GET request with http://localhost:40000/odata/Employees/$count?$filter=Region eq ‘WA’

Get a Count of the Number of Employees and Include Count

We can also include the count as part of the JSON when retrieving Employees.

From Postman issue a GET request with http://localhost:40000/odata/Employees?$count=true

That’s it for count. In the next blog I’ll take a look at the $apply query option.