title: Web API Queryable - how to apply AutoMapper?
body: <p>I've got a simple WebApi method like this decorated with the OData queryable attribute.</p>
  
  <pre><code>    [Queryable]
      public virtual IQueryable&lt;PersonDto&gt; Get()
      {
          return uow.Person().GetAll()); // Currently returns Person instead of PersonD
      }
  </code></pre>
  
  <p>What I want to do is transform the result of the query from type Person to type PersonDto using AutoMapper before WebAPI converts the result to JSON.</p>
  
  <p>Does anybody know how I can do this? I am aware, I could apply Mapper.Map after the GetAll() call and then convert back to IQueryable, however this would result in the entire table being returned and mapped before the OData filter is applied (not good!).</p>
  
  <p>It would appear that this question <a href="https://stackoverflow.com/questions/9894369/asp-net-web-api-return-queryable-dtos">ASP.NET Web API return queryable DTOs?</a> covers the same issue (see second response for a better answer), where the suggestion is to use AutoMapper at the end of the chain using a custom MediaTypeFormatter, however I have no idea how to do that based on the example I have seen.</p>
  
  <p>Any help will be gratefully received!</p>
  
  <p>-- Further Info</p>
  
  <p>I've looked at the source code for IQueryable, but unfortunately there I can't see any way of utilising the code for this purpose. I have managed to write an additional filter which appears to work, however it isn't certainly isn't elegant. </p>
  
  <pre><code>public class PersonToPersonDtoConvertAttribute : ActionFilterAttribute
  {
      public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
      {
          HttpResponseMessage response = actionExecutedContext.Response;
  
          if (response != null)
          {
              ObjectContent responseContent = response.Content as ObjectContent;
              var query = (responseContent.Value as IQueryable&lt;Student&gt;).ToList();
              response.Content = new ObjectContent&lt;IEnumerable&lt;StudentResource&gt;&gt;(query.ToList().Select(Mapper.Map&lt;Person, PersonDto&gt;), responseContent.Formatter);
          }
      }
  }
  </code></pre>
  
  <p>Then I have decorated the action like </p>
  
  <pre><code>    [Queryable]
      [PersonToPersonDtoConvert]
      public IQueryable&lt;Person&gt; Get()
      {
          return uow.GetRepo&lt;IRepository&lt;Person&gt;&gt;().GetAll();
      }
  </code></pre>