Getting started with OData v4 in ASP.NET Web API - StrathWeb

Strath

February 18th, 2014

Getting started with OData v4 in ASP.NET Web API

Because v4 is almost here!

Since yesterday, the ASP.NET Web stack nightly feed contains the packages supporting OData v4. The package is called Microsoft.AspNet.OData and has a working version 5.2.0 – so I’m guessing this is intended to ship with Web API 2.

It relies on the latest beta of Microsoft.OData.Core. OData v4 is a massive changed compared to v3 – you can read about all of them here.

Adding OData v4 to your Web API

You need to use the Web stack nightlies which is available at http://www.myget.org/F/aspnetwebstacknightly/ and needs to be added to your Nuget repositories.

nightlies

Once added, you can install the new OData nightly packages using:

If your Web API has a reference to Microsoft.AspNet.WebApi.OData (the old OData support package), it should be removed. Also, you may have to add assembly binding redirects – since Microsoft.AspNet.OData will pull latest nightlies of Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.Client, which will replace your current references to those packages.

Below are the necessary redirects:

Getting started with OData v4 in Web API

I’ll use a simple model and a DbContext for this exercise:

The controller is the same one as you’d get using scaffolding, with some small changes done to cater for the new OData package. Notice that we now use [EnableQuery] instead of [Queryable]. Also, with OData v4 we could (should?) support upsert (insert with PUT), but I will not do that.

Registration is done in the same way as before, except the MapODataRoute is replaced with MapODataServiceRoute method.

With these in place, I also added DB migrations using the following steps:

  1. 1. run enable-migrations from the package manager console
  2. 2. updated the generated Configuration.cs with my sample data
  3. 3. added initial migration with add-migration Initial command
  4. 4. executed the DB update using update-database

Next step is to run the whole solution and navigate to the $metadata to see what version of OData we are running – and indeed it is v4.

odata

In OData v4, $inlinecount has been replaced with $count.

count

getall

getplayer

While these are only nightlies, it’s great to see the progress on the OData v4 front. So go ahead and start playing with the next generation web services built on top of OData v4!

Be Sociable, Share!