2
votes

I have controllers that inherit from ApiController. I have the EnableQuery attribute at the top of it to allow ODATA query strings. However $count does not work.

For eg:- ../products?$count=true does return data with no odataexception, but does not return the count. Any suggestions

1
Please show us your server side code and the payload you get from the server(json). - gdoron is supporting Monica
Since you are using ODATA queries, I suggest you inherit your controllers inheriting from ODataController instead of ApiController and then you can refer to the aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/… - QianLi
I've got the same problem, and making them inherit from ODataController means registering the functions and types with the OData model, which can't handle very dynamic types. - Mant101

1 Answers

0
votes

You can get count separately and put it in new dictionary together with data, returning this dictionary in the method of your controller. The following code applies all that was specified in OData query (including select, expand and filter) and returns both data and count:

public class ProductsController : ApiController
{    
    public IHttpActionResult Get(ODataQueryOptions<Product> queryOptions)
    {
        IQueryable<Product> products = ... ///any IQueryable<Product>
        var results = queryOptions.ApplyTo(products);
        var dict = new Dictionary<string, object>();
        if (Request.ODataProperties().TotalCount != null)
        {
            dict.Add("@odata.count", Request.ODataProperties().TotalCount);
        }
        dict.Add("value", results);
        return Ok(dict);
    }
}

However, to use ODATA in a way recommended by ASP.NET Web API documentation, you'll need to use ODataController instead of ApiController