Search code examples
collectionscountodata

How can i do a Count of Collection using Asp.net , Web API 2 and OData v4


I want to order results based on a count of collection using Asp.net, web api2 and OData v4.

My url is: url/odata/groupeclients?$expand=Client&$orderby=Client/$count

I get this error :

"The query specified in the URI is not valid. The parent value for a property access of a property '$count' is not a single value. Property access can only be applied to a single value."

Is this supported in Web API OData? If not, is there any alternative solution?

Regards, Hayfa


Solution

  • It's not currently supported; there's an open issue.

    As a workaround, you could define an OData function bound to groupeclients that explicitly performs the expansion and ordering. Something like:

    [HttpGet]
    public IHttpActionResult OrderByClientCount()
    {
        return this.Ok(data.Include(e => e.Client).OrderBy(e => e.Client.Count));
    }
    

    Note that this code is untested and may not even be possible if your IQueryable data source does not support Include (or its equivalent).