Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen is ObjectQuery really an IOrderedQueryable?
    primarykey
    data
    text
    <p>Applied to entity framework, the extension methods <code>Select()</code> and <code>OrderBy()</code> both return an <code>ObjectQuery</code>, which is defined as:</p> <pre><code>public class ObjectQuery&lt;T&gt; : ObjectQuery, IOrderedQueryable&lt;T&gt;, IQueryable&lt;T&gt;, &lt;... more interfaces&gt; </code></pre> <p>The return type of <code>Select()</code> is <code>IQueryable&lt;T&gt;</code> and that of <code>OrderBy</code> is <code>IOrderedQueryable&lt;T&gt;</code>. So you could say that both return the same type but in a different wrapper. Luckily so, because now we can apply <code>ThenBy</code> after <code>OrderBy</code> was called.</p> <p>Now my problem.</p> <p>Let's say I have this:</p> <pre><code>var query = context.Plots.Where(p =&gt; p.TrialId == 21); </code></pre> <p>This gives me an <code>IQueryable&lt;Plot&gt;</code>, which is an <code>ObjectQuery&lt;Plot&gt;</code>. But it is also an IOrderedQueryable:</p> <pre><code>var b = query is IOrderedQueryable&lt;Plot&gt;; // True! </code></pre> <p>But still:</p> <pre><code>var query2 = query.ThenBy(p =&gt; p.Number); // Does not compile. // 'IQueryable&lt;Plot&gt;' does not contain a definition for 'ThenBy' // and no extension method 'ThenBy' .... </code></pre> <p>When I do:</p> <pre><code>var query2 = ((IOrderedQueryable&lt;Plot&gt;)query).ThenBy(p =&gt; p.Number); </code></pre> <p>It compiles, but gives a runtime exception:</p> <blockquote> <p>Expression of type '<code>IQueryable`1[Plot]</code>' cannot be used for parameter of type <code>'IOrderedQueryable`1[Plot]</code>' of method '<code>IOrderedQueryable`1[Plot] ThenBy[Plot,Nullable`1](IOrderedQueryable`1[Plot], Expressions.Expression`1[System.Func`2[Plot,System.Nullable`1[System.Int32]]])</code>'</p> </blockquote> <p>The cast is carried out (I checked), but the parameter of <code>ThenBy</code> is still seen as IQueryable (which puzzles me a bit).</p> <p>Now suppose some method returns an <code>ObjectQuery&lt;Plot&gt;</code> to me as <code>IQueryable&lt;Plot&gt;</code> (like <code>Select()</code>). What if I want to know whether it is safe to call <code>ThenBy</code> on the returned object. How can I figure it out if the <code>ObjectQuery</code> is "real" or a "fake" <code>IOrderedQueryable</code> without catching exeptions?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload