title: How to enable $expand and $select on ODataQueryOptions?
body: <p>The issue started <a href="https://stackoverflow.com/questions/21647830/is-it-possible-to-use-odataqueryoptions-with-dtos/21685416?noredirect=1#comment32784822_21685416">here</a>, where I am unable to call <code>$select</code> or <code>$expand</code> on <code>results</code>.</p>
  
  <p>Given: </p>
  
  <pre><code>            var results = options.ApplyTo(_uow.Repository&lt;ContentType&gt;()
                  .Query()
                  .Get()
                  .Include(u =&gt; u.User)
                  .Where(u =&gt; u.UserId == userId)
                  .OrderBy(o =&gt; o.Description)).Cast&lt;ContentType&gt;()
                  .Select(x =&gt; new ContentTypeDTO()
                  {
                      //projection goes here
                      ContentTypeId = x.ContentTypeId,
                      Description = x.Description,
                      UserDTO = new UserDTO 
                      { 
                          UserId = x.UserId,
                          UserName = x.User.UserName
                      }
                  });
  </code></pre>
  
  <p>Exception:</p>
  
  <blockquote>
    <p>Unable to cast the type
    'System.Web.Http.OData.Query.Expressions.SelectExpandBinder+SelectSome`1[[Project.DAL.Data.Models.ContentType,
    Project.DAL.Data, Version=1.0.0.0, Culture=neutral,
    PublicKeyToken=null]]' to type 'Project.DAL.Data.Models.ContentType'. 
    LINQ to Entities only supports casting EDM primitive or enumeration
    types."</p>
  </blockquote>
  
  <p>Based on <a href="https://stackoverflow.com/questions/18879779/select-and-expand-break-odataqueryoptions-how-to-fix">this solution</a>, I understand that when <code>$select</code> or <code>$expand</code> are applied to the result, it is no longer a <code>ContentType</code>, as is expected by the <code>Cast&lt;ContentType&gt;()</code>.  That solution uses <code>HierarchyNodeExpressionVisitor</code>, which I am unable to locate.</p>
  
  <p>I want to use 'options.ApplyTo()' as I want the filtering done on the db server, to ensure I don't get back an inflated data set with hundreds of thousands of rows.</p>
  
  <p>Is there a suggested way of getting around this?</p>
  
  <p><strong>-- UPDATE --</strong></p>
  
  <p>In using @Schandlich 's suggested solution below, the operation still fails with the <code>Ok</code> override:</p>
  
  <p><strong>Locals:</strong></p>
  
  <pre><code>+       this    {Project.AdminWebsite.Api.Controllers.ContentTypeController}    Project.AdminWebsite.Api.Controllers.ODataBaseController {Project.AdminWebsite.Api.Controllers.ContentTypeController}
  +       content {System.Data.Entity.Infrastructure.DbQuery&lt;Project.Core.UI.Models.ContentTypeDTO&gt;}  object {System.Data.Entity.Infrastructure.DbQuery&lt;Project.Core.UI.Models.ContentTypeDTO&gt;}
  +       type    {Name = "DbQuery`1" FullName = "System.Data.Entity.Infrastructure.DbQuery`1[[Project.Core.UI.Models.ContentTypeDTO, Project.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"} System.Type {System.RuntimeType}
  +       resultType  {Name = "OkNegotiatedContentResult`1" FullName = "System.Web.Http.Results.OkNegotiatedContentResult`1[[System.Data.Entity.Infrastructure.DbQuery`1[[Project.Core.UI.Models.ContentTypeDTO, Project.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"}    System.Type {System.RuntimeType}
  +       result  {System.Web.Http.Results.OkNegotiatedContentResult&lt;System.Data.Entity.Infrastructure.DbQuery&lt;Project.Core.UI.Models.ContentTypeDTO&gt;&gt;}   System.Web.Http.IHttpActionResult {System.Web.Http.Results.OkNegotiatedContentResult&lt;System.Data.Entity.Infrastructure.DbQuery&lt;Project.Core.UI.Models.ContentTypeDTO&gt;&gt;}
  </code></pre>
  
  <p><strong>Call stack:</strong></p>
  
  <pre><code>&gt;   Project.AdminWebsite.dll!Project.AdminWebsite.Api.Controllers.ODataBaseController.Ok(object content, System.Type type) Line 27  C#
      Project.AdminWebsite.dll!Project.AdminWebsite.Api.Controllers.ContentTypeController.Get(System.Web.Http.OData.Query.ODataQueryOptions&lt;Project.DAL.Data.Models.ContentType&gt; odataQueryOptions) Line 132  C#
      [Lightweight Function]  
      System.Web.Http.dll!System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.GetExecutor.AnonymousMethod__9(object instance, object[] methodParameters) Unknown
      System.Web.Http.dll!System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(object instance, object[] arguments)   Unknown
      System.Web.Http.dll!System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Collections.Generic.IDictionary&lt;string,object&gt; arguments, System.Threading.CancellationToken cancellationToken)  Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpActionDescriptorTracer.ExecuteAsync.AnonymousMethod__1()    Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync&lt;object&gt;(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action&lt;System.Web.Http.Tracing.TraceRecord&gt; beginTrace, System.Func&lt;System.Threading.Tasks.Task&lt;object&gt;&gt; execute, System.Action&lt;System.Web.Http.Tracing.TraceRecord,object&gt; endTrace, System.Action&lt;System.Web.Http.Tracing.TraceRecord&gt; errorTrace)   Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpActionDescriptorTracer.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Collections.Generic.IDictionary&lt;string,object&gt; arguments, System.Threading.CancellationToken cancellationToken) Unknown
      System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore()  Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start&lt;System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore&gt;(ref System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore stateMachine)  Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder&lt;System.__Canon&gt;.Start&lt;System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore&gt;(ref System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore stateMachine)  Unknown
      System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) Unknown
      System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpActionInvokerTracer.System.Web.Http.Controllers.IHttpActionInvoker.InvokeActionAsync.AnonymousMethod__1()   Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync&lt;System.Net.Http.HttpResponseMessage&gt;(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action&lt;System.Web.Http.Tracing.TraceRecord&gt; beginTrace, System.Func&lt;System.Threading.Tasks.Task&lt;System.Net.Http.HttpResponseMessage&gt;&gt; execute, System.Action&lt;System.Web.Http.Tracing.TraceRecord,System.Net.Http.HttpResponseMessage&gt; endTrace, System.Action&lt;System.Web.Http.Tracing.TraceRecord&gt; errorTrace)    Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpActionInvokerTracer.System.Web.Http.Controllers.IHttpActionInvoker.InvokeActionAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) Unknown
      System.Web.Http.dll!System.Web.Http.Controllers.ActionFilterResult.ActionInvoker.InvokeActionAsync()    Unknown
      System.Web.Http.dll!System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync()   Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start&lt;System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync&gt;(ref System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync stateMachine)    Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder&lt;System.__Canon&gt;.Start&lt;System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync&gt;(ref System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync stateMachine)    Unknown
      System.Web.Http.dll!System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync(System.Threading.CancellationToken cancellationToken)   Unknown
      System.Web.Http.dll!System.Web.Http.ApiController.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken)   Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore() Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start&lt;System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore&gt;(ref System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore stateMachine)    Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder&lt;System.__Canon&gt;.Start&lt;System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore&gt;(ref System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore stateMachine)    Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpControllerTracer.ExecuteAsyncCore(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken)    Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpControllerTracer.System.Web.Http.Controllers.IHttpController.ExecuteAsync.AnonymousMethod__0()  Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync&lt;System.Net.Http.HttpResponseMessage&gt;(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action&lt;System.Web.Http.Tracing.TraceRecord&gt; beginTrace, System.Func&lt;System.Threading.Tasks.Task&lt;System.Net.Http.HttpResponseMessage&gt;&gt; execute, System.Action&lt;System.Web.Http.Tracing.TraceRecord,System.Net.Http.HttpResponseMessage&gt; endTrace, System.Action&lt;System.Web.Http.Tracing.TraceRecord&gt; errorTrace)    Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.Tracers.HttpControllerTracer.System.Web.Http.Controllers.IHttpController.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken)    Unknown
      System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
      System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync() Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start&lt;System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync&gt;(ref System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync stateMachine)    Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder&lt;System.__Canon&gt;.Start&lt;System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync&gt;(ref System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync stateMachine)    Unknown
      System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
      System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)  Unknown
      System.Web.Http.dll!System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)    Unknown
      System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)   Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.AnonymousMethod__FabricatedMethod6()    Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.SendAsync.AnonymousMethod__1()  Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync&lt;System.Net.Http.HttpResponseMessage&gt;(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action&lt;System.Web.Http.Tracing.TraceRecord&gt; beginTrace, System.Func&lt;System.Threading.Tasks.Task&lt;System.Net.Http.HttpResponseMessage&gt;&gt; execute, System.Action&lt;System.Web.Http.Tracing.TraceRecord,System.Net.Http.HttpResponseMessage&gt; endTrace, System.Action&lt;System.Web.Http.Tracing.TraceRecord&gt; errorTrace)    Unknown
      System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
      System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)   Unknown
      System.Web.Http.dll!System.Web.Http.HttpServer.AnonymousMethod__FabricatedMethod9() Unknown
      System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync()  Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start&lt;System.Web.Http.HttpServer.SendAsync&gt;(ref System.Web.Http.HttpServer.SendAsync stateMachine)  Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder&lt;System.__Canon&gt;.Start&lt;System.Web.Http.HttpServer.SendAsync&gt;(ref System.Web.Http.HttpServer.SendAsync stateMachine)  Unknown
      System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)  Unknown
      System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)  Unknown
      System.Web.Http.WebHost.dll!System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore() Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start&lt;System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore&gt;(ref System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore stateMachine)    Unknown
      mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start&lt;System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore&gt;(ref System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore stateMachine)    Unknown
      System.Web.Http.WebHost.dll!System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore(System.Web.HttpContextBase contextBase)   Unknown
      System.Web.Http.WebHost.dll!System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsync(System.Web.HttpContext context)   Unknown
      System.Web.dll!System.Web.HttpTaskAsyncHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest.AnonymousMethod__0()    Unknown
      System.Web.dll!System.Web.TaskAsyncHelper.BeginTask(System.Func&lt;System.Threading.Tasks.Task&gt; taskFunc, System.AsyncCallback callback, object state) Unknown
      System.Web.dll!System.Web.HttpTaskAsyncHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(System.Web.HttpContext context, System.AsyncCallback cb, object extraData)  Unknown
      System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()  Unknown
      System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step, ref bool completedSynchronously)  Unknown
      System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error)   Unknown
      System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext context, System.AsyncCallback cb)  Unknown
      System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr, System.Web.HttpContext context)    Unknown
      System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
      System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)   Unknown
      [Native to Managed Transition]  
      [Managed to Native Transition]  
      System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
      System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags)   Unknown
      [AppDomain Transition]  
  </code></pre>
  
  <p>Error Message:</p>
  
  <pre><code>Unable to cast the type 'System.Web.Http.OData.Query.Expressions.SelectExpandBinder+SelectAll`1[[Project.DAL.Data.Models.ContentType, Project.DAL.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' to type 'Project.DAL.Data.Models.ContentType'. LINQ to Entities only supports casting EDM primitive or enumeration types.
  </code></pre>