title: Linq to Entities - Custom method (OrderBy) fails in lambda statement
body: <p>I am trying to write a custom OrderBy extension method for Linq to Entities, where I can sort ASC or DESC based on a parameter. My first attempt was the following:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public static class LinqExtensions
  {   
      public static IOrderedQueryable&lt;TSource&gt; OrderByExtension&lt;TSource, TKey&gt;(this IQueryable&lt;TSource&gt; source, Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector, bool isDescending = true)
      {
          return (isDescending) ? source.OrderByDescending(keySelector) : source.OrderBy(keySelector);
      }
  }
  </code></pre>
  
  <p>This works great!... As long as I don't use this method inside a lambda statement. A toy example would be:</p>
  
  <pre class="lang-cs prettyprint-override"><code>using (var dbContext = new FooDBEntities())
  {
      var foo = dbContext.Fubars.SelectMany(x =&gt; dbContext.Fubars.OrderByExtension(y =&gt; y.Foo, true)).ToList();
  }
  </code></pre>
  
  <p>When I run the above code the program blows out and I get the following error:</p>
  
  <pre><code>Unhandled Exception: System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Linq.IOrderedQueryable`1[ExpressionTreeFoo.Fubar] OrderByExtension[Fubar,String](System.Linq.IQueryable`1[ExpressionTreeFoo.Fubar], System.Linq.Expressions.Expression`1[System.Func`2[ExpressionTreeFoo.Fubar,System.String]], Boolean)' method, and this method cannot be translated into a store expression.
  </code></pre>
  
  <p>The error pretty much says it all. The framework does not know how to translate my custom extension method into something that SQL can understand. </p>
  
  <p>I've been doing some googling but I haven't seen anything that says definitively that this is or is not possible. So my question is.. Is there any way at all to make a custom OrderBy method (extension method or not) that will work inside a lambda expression?</p>