Search code examples
asp.net-web-apiodata

Returning OData count for non-entity set collections


I have an action routed that returns a non-entity collection.

ActionConfiguration previewInvoices = this.EntityType.Collection.Action("PreviewInvoices");
previewInvoices.ReturnsCollection<InvoicePreviewComponent>();

Now when I query to get the results, I am using a $take=20 to control paging through javascript. However it doesn't return a count as it does with entity sets with $inlinecount=allpages.

One solution I had been doing was to change the lines to:

ActionConfiguration previewInvoices = this.EntityType.Collection.Action("PreviewInvoices");
previewInvoices.ReturnsCollectionFromCollection<InvoicePreviewComponent>("InvoicePreviewComponent");

However this generates ghost entity sets in the $metadata, which I am using to generate the javascript models and requests. Not ideal, and ultimately not correct to annotate this as an entity set.

How can I modify the response JSON formatter to give the count as requested?


Solution

  • The count value of non-entity collection won't be serialized into the response body.

    But you can get the count value by the following code:

    response.RequestMessage.ODataProperties().TotalCount
    

    (Note: ODataProperties() is an extension method in static class System.Web.Http.OData.Extensions.HttpRequestMessageExtensions)