Peter Goodman bio photo

Peter Goodman

A software engineer and leader living in Auckland building products and teams. Originally from Derry, 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)