Search code examples
c#asp.netodata

How to use OData $orderby with functions


I am querying data from backend server by Rest API using OData v3.0.

I have a table (and the associated resource URL) Contact and each contact has either CompanyName or PersonName. How ever in frontend there's only a Name displayed.

What I want to achieve is to $orderby these two fields whichever is available. A possible way is the concatenation of these two fields, for example $orderby=concat(CompanyName,PersonName), but I got this error

Please check your OData query: Only ordering by properties at the root level is supported for non-primitive collections. Nested properties and expressions are not supported.

Is there any other way I can do this orderby? Thanks.


Solution

  • The question

    How can I order by EITHER one field or the other?

    The hypothetical answer

    You can use an expression in your orderby, as you did, here is a working example:

    https://services.odata.org/V3/Northwind/Northwind.svc/Customers/?$orderby=concat(Phone,Fax)

    But why does it not work?

    According to the ODATA specification, this should work, but the truth is, that most backend implementations do not full comply to the specification. That is a pretty normal thing.

    Many backend implementations I know just do not SUPPORT nested properties or expressions in its orderby.

    Especially when the backend is provided by systems that base on relational databases (older SAP Systems, NAV or AX Systems..) they tend to not support it, mostly because they want to directly push the query down to the database, or they just didnt implement it up to this day.

    You never can assume that the backend completely implements the whole ODATA specs, most of the time, the backend implements only what was needed so far.

    So, the practical answer

    This is not an ODATA specification problem. Your approach is correct. Instead, you have a not fully implemented backend. Your only solution is to ask them to implement it, or handle it on the client side.

    By the way

    ODATA v3 is a very strange and rarely supported version of ODATA. Normally, there is ODataV2 or ODataV4 around nowadays.