0
votes

I have a API controller with the following method used to retrieve one specific object. The output is formatted in Json.

[Route("~/api/orders({key:int})", Name = "GetOrder")]
public IHttpActionResult GetOrder([FromODataUri] int key, ODataQueryOptions<Order> queryOptions)

It works as follows.

  1. Build up a base query from Entity Framework named baseQuery
  2. Apply the Odata filters to the base query using

    queryOptions.ApplyTo(baseQuery.OrderByDescending(f => f.Id) , querySettings);

  3. Return the resulting IQueryable

The problem is that this results in a list containing one object (the one asked for). I would like to have it return the object itself rather then a list with the object.

I have tried adding FirstOrDefault() to the baseQuery but that causes the query to be executed and the OData filter cannot be applied after that.

1

1 Answers

1
votes

Use System.Web.Http.SingleResult can make this work

SingleResult.Create(queryable)

Example:

[EnableQuery]
[ODataRoute("Order({orderId})")]
public SingleResult<Order> Get(int orderId)
{
    var result = _myOrders.AsQueryable().Where(mo => mo.ID == orderId);
    return SingleResult.Create(result);
}

QueryOptions will apply after result return in controller because of EnableQuery Attribute.