Search code examples
c#odataasp.net-web-api2scaffolding

OData V4 property access


I have created a very primitive OData webservice using a Visual Studio 2015 Web API 2 project and a scaffolded controller ("Microsoft OData V4 Web API Controller Using Entity Framework" scaffolding).

I have only one entity set in my model: "Books". The "Book" entity has a privimtive "Title" string property.

I presumed that the scaffolded controller would serve all legal OData v4 requests, but that seems not to be the case?

http://localhost:xxxx/OData/Books works (enumerates all books with all properties - including the "Title" property)

http://localhost:xxxx/OData/Books(1) works (enumerates all properties on the first book, including the "Title" property)

http://localhost:xxxx/OData/Books(1)/Title does not work - I get a "No routing convention was found to select an action for the OData path with template '~/entityset/key/property" error, despite that the request is 100% OData v4 complaint?

Why doesn't it work? Shouldn't it work? What will it take to make it work?


Solution

  • The scaffolding does not create a controller that serves all legal OData v4 requests.

    To retrieve the Title property of a Book entity, you must add a method to the BooksController as follows:

    public string GetTitleFromBook([FromODataUri] int key) 
    {
        // Put appropriate method logic here.
    }
    

    See "Querying a Navigation Property" and "Properties" tables in Routing Conventions in ASP.NET Web API 2 Odata.

    Also, consider using the $select query option to limit the properties you get in response to a normal request for an entity. For example:

    GET http://localhost:xxxx/OData/Books(1)?$select=Title