Mister Epic
Mister Epic

Reputation: 16743

Web API and queries with foreign keys

I'm playing around with Web API, and I'm struggling a bit with creating queries to pull back data based on a filter. The classic example would be pulling back a list of items based on a foreign key.

Let's say I have the following entity:

Movie
======
id
directorId
categoryId

It would not be uncommon for me to build a DAO with the following methods:

MovieRepo.GetByDirector(int directoryId);
MovieRepo.GetByCategory(int category);

Recently, I have been using Linq and the Entity Framework to build retrieval methods that can be used by multiple calling clients, but whose returned list can filtered based on whatever criteria is passed to a filter

public IEnumerable<Movie> Get(MovieFilter filter){
    IQueryable<Movie> query = _context.tblMovie;

    if(!String.IsNullOrEmpty(filter.directorId))
         query.Where(m => m.directoryId == filter.directorId);

    if(!String.IsNullOrEmpty(filter.categoryId))
          query.Where(m => m.categoryId == filter.categoryId);

    return query.ToList();
}

The boilerplate Web API controller actions are:

IEnumerable<Movie> Get();
Movie Get(int id)

If I wanted to filter my query by directory or category with Web API, how exactly would I do it in a RESTful way? Given the way routing gets resolved, the following would be an ambiguous call:

IEnumerable<Movie> GetByCategory(int categoryId);

I haven't see much guidance on this, can someone provide some for me?

Regards,

Chris

Upvotes: 3

Views: 2437

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123901

One of the ways is to use OData protocol http://www.odata.org/docs/

There is also a library supporting OData filtering http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api, supporting querying over the IQueryable interface

It could be seen as a bit more complex, but you gain a lot. Parts of the OData standard :

  • $filter - Filters the results, based on a Boolean condition.
  • $select - which columns/properties should be selected
  • $inlinecount - Tells the server to include the total count of matching entities in the response. (Useful for server-side paging.)
  • $orderby - Sorts the results.
  • $skip - Skips the first n results.
  • $top - Returns only the first n the results.

Honestly, we are using the OData ... while not using the IQueryable and MS libraries. We just created own parser, supporting only limited stuff. But there is OData standard in place

Upvotes: 1

Related Questions