Query composition with the ASP.NET Web API
Wednesday 21 March 2012
As we have seen in a previous post just returning a collection data was real easy.
As it turns out changing the service so the client can filter data is almost just as easy. In the previous example we returned an IEnumerable<Product>. All we need to di is change this to return an IQueryable<Product> and most of the work is done.
Loading the products with the original URL returns exactly the same result as before.
But now the client can also decide to order and filter data. This request “http://localhost:6876/api/Products?$orderby=ProductName&$skip=10&$top=5” returns only product 11 to 15 ordered by the product name.
You can also search for specific data using the $filter clause like this “http://localhost:6876/api/Products?$filter=ProductName eq 'Chocolade'”
Or something like “http://localhost:6876/api/Products?$filter=startswith(ProductName, 'Cha')”
Sweet right? And all of that by just changing IEnumerable<T> to IQueryable<T>
In fact the only thing I would like to see added to this was projections. After all we don’t do a “Select * from Table where …” either right?