Part 12 – OData v4 in ASP.NET WebApi – Selecting Properties

oneThis is a series of blogs detailing my introduction to using OData v4 with C# and ASP.NET WebApi.

The source code for the project can be found here.

Get a Specific Property

We have seen how OData allows us to retrieve an entire entity set collection and an individual collection. What the standard also allows us to do is pulling out a property from an entity.

From Postman issue a GET request with http://localhost:40000/OData/Cars(Make=’Vauxhall’,Model=’Zafira’) to fetch a single car.

What if we only want to return the Price?

From Postman issue a GET request with http://localhost:40000/OData/Cars(Make=’Vauxhall’,Model=’Zafira’)/Price to fetch a single car.

We get an error. This is because we do not have an action for this request. In a later blog I will be discussing the $SELECT query option which offers us more flexibility.

Add Action to Controller Class

Create an action method called GetCarPrice.

[ODataRoute("(Make={KeyMake}, Model={KeyModel})/Price")]
public IHttpActionResult GetCarPrice([FromODataUri] string KeyMake, [FromODataUri] string KeyModel)
{
   var _car = _repo.GetCar(KeyMake, KeyModel);
   if (_car == null)
   {
      return NotFound();
   }

   return Ok(_car.Price);
}

This method is specifically written for Price. We can create a generic method that reads the property from the URL and using reflection we can retrieve the value.

From Postman issue a GET request with http://localhost:40000/OData/Cars(Make=’Vauxhall’,Model=’Zafira’)/Price to fetch a single car.

The value is returned however; it is wrapped in JSON.

Get the Property Raw Value

The OData specification says that we can fetch the raw value without the JSON or OData attributes if we append $value to the url. Let’s try that.

From Postman issue a GET request with http://localhost:40000/OData/Cars(Make=’Vauxhall’,Model=’Zafira’)/Price/$value

We get the same error as before but all we need to do is add a route attribute. The framework takes care of returning just a string.

[ODataRoute("(Make={KeyMake}, Model={KeyModel})/Price")]
[ODataRoute("(Make={KeyMake}, Model={KeyModel})/Price/$value")]
public IHttpActionResult GetCarPrice([FromODataUri] string KeyMake, [FromODataUri] string KeyModel)
{
   var _car = _repo.GetCar(KeyMake, KeyModel);
   if (_car == null)
   {
      return NotFound();
   }

   return Ok(_car.Price);
}

From Postman issue a GET request with http://localhost:40000/OData/Cars(Make=’Vauxhall’,Model=’Zafira’)/Price/$value

In the next blog I will look at relations