1

I'd like to configure a route that always returns a single entity.

The controller looks like:

class StatsController: ODataController { public Stats Get() { return new Stats(); } } The url to access it should be: GET ~/service-prefix/stats

All the options I've seen involve having to return IQueryable, or when returning a single entity, passing in a key in a form of ~/service-prefix/EntitySet(1)

Is there a way to achieve the above without having to return an IQueriable?

Oleg D.
  • 1,184
  • 11
  • 20
  • Per the OData protocol, the path segment after service-prefix is mostly an entity set, which means a collection of entities will be returned. May I know that why you want only ONE entity instead of a collection by requesting such a URL? – Tan Jinfu Mar 18 '14 at 13:02
  • @tanjinfu Conceptually the endpoint will always return a single object. The object represent a current state of the application, which is never a collection. – Oleg D. Mar 18 '14 at 15:27
  • Thank you for the reply. I've posted my answer. – Tan Jinfu Mar 19 '14 at 00:01

3 Answers3

0

By default any action of the following forms should be reachable for your scenario:

Example:

public Stat Get([FromODataUri] int key) { }

or

public Stat Get#your-entity-name#([FromODataUri] int key) { }

Kiran
  • 56,921
  • 15
  • 176
  • 161
0

To access a single object without needing to have an entityset, odata v4 introduces the concept of singletons.

From OData v4 spec:

A singleton allows addressing a single entity directly from the entity container without having to know its key, and without requiring an entity set.

More info:

Oleg D.
  • 1,184
  • 11
  • 20
  • hmm..how is this `Singleton` related to your question? – Kiran Mar 18 '14 at 19:47
  • @KiranChalla, the concept of singleton in the context of the OData api is exactly what I needed: a single entity that service provides, which is never in the collection, and which can be addressed without having to provide an index – Oleg D. Jul 03 '14 at 19:02
0

I believe Singleton could meet your requirement, but it is not implemented in WebApi. Fortunately, there is another option: unbound function. Just follow this sample: http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ODataFunctionSample/.

There is a method in ProductsController:

    [HttpGet]
    [ODataRoute("GetSalesTaxRate(state={state})")]
    public IHttpActionResult GetSalesTaxRate([FromODataUri] string state)
    {
        return Ok(GetRate(state));
    }

It is requested through this URL: ~/service-prefix/GetSalesTaxReate(state='WA') and is very close to your scenario. The only thing you need to do is to remove the parameter of the function:

    [HttpGet]
    [ODataRoute("GetStats()")]
    public IHttpActionResult GetStats()
    {
        return Ok(new Stats());
    }

Now you can request ~/sevice-prefix/GetStats().

Tan Jinfu
  • 3,327
  • 1
  • 19
  • 20