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 do is change this to return an IQueryable<Product> instead of an IEnumerable<Product> and most of the work is done.
1: public class ProductsController : ApiController
3: private NorthwindContext _db = new NorthwindContext();
5: // GET /api/<controller>
6: public IQueryable<Product> Get()
8: return _db.Products;
11: // GET /api/<controller>/5
12: public Product Get(int id)
14: return _db.Products.Single(p => p.ProductID == id);
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?