title: OData filtering before selecting inside an expand query
body: <p>I am writing a query for metadata in Dynamics 365, but I think this problem could be universal for any OData query.</p>
  
  <p>My problem is as follow: </p>
  
  <p>In Dynamics, we can have multiple types of fields in entities, such as strings, bools or lookup. I want to write a query that returns the type of entity the lookup is addressing.</p>
  
  <pre><code>{url}/api/data/v9.0/EntityDefinitions(LogicalName='Account')
  ?$select=
      LogicalName
  &amp;$expand=
      Attributes(
          $select=
              LogicalName,
              AttributeType,
              Targets; -- Problematic property
          $filter=
        AttributeType+eq+Microsoft.Dynamics.CRM.AttributeTypeCode'Lookup')
  </code></pre>
  
  <p>If I dont include the select for Targets in this query, I get the correct result, being all attributes where theyr AttributeType is Lookup. </p>
  
  <p>But when I require the Targets to be aslo included, I get an error message </p>
  
  <pre><code>Could not find a property named 'Targets' on type 'Microsoft.Dynamics.CRM.AttributeMetadata
  </code></pre>
  
  <p>Because the Target property only exists on those arrribute that are of the type Lookup, therefore selecting this column from a string attribute will fail and throw this error.</p>
  
  <p>Is there a way to first filter to lookups before selecting a column? I have found <a href="https://msdn.microsoft.com/en-us/library/dd541392.aspx" rel="noreferrer">here</a> that the order of evaluation is </p>
  
  <p><strong>$filter, $inlinecount, $orderby, $skiptoken, $skip, $top, $expand, $select, $format</strong></p>
  
  <p>which is exactly what I need, except I don't think this order is the same when invoked inside the $expand attribute.</p>