Peter Goodman bio photo

Peter Goodman

A developer living in Auckland building software using all sorts of bits and pieces I find along the way. Originally from Northern Ireland.

Twitter Google+ LinkedIn Github

Back in March I wrote a quick howto on supporting $expand for entities in ASP.Net Web API. That method used an extension method to pull the $expand clause out of the query string an apply it to the ObjectSet.

I’ve now added to that sample an ActionFilter which will do this for you without any code in your controller.

To use it, change your global.asax and add the ActionFilter as part of your configuration.

public static void RegisterRoutes(RouteCollection routes) {
    ...
    ...

    HttpConfiguration configuration = GlobalConfiguration.Configuration;
    configuration.Filters.Add(new EFExpandActionFilter());

    ...
    ... 
    ...
}

 

Now your api methods need only return an ObjectSet or ObjectQuery without any extension methods.

public IQueryable<Customer> GetCustomers() {
    return northwindEntities.Customers;
}

Note that if you are using the default XML serializer you will find that the navigation properties do not serialize due to the XmlIgnore attribute, either customize your entities or use Json.Net (as in the sample project)