title: Using a custom extension method in an Entity Framework GroupBy
body: <p>In my application I'm calculating the geometric mean a few different places, and would like to have the implementation in one place, so as to cause less confusion for maintainers. For performance reasons I need the calculation to happen in the database, so fetching the data and running <code>GeoMean()</code> in C# is not an option.</p>
  <p>However, I can't figure out how to write an extension method that I can use in my code. The query looks something like this:</p>
  <pre class="lang-cs prettyprint-override"><code>data.GroupBy(a =&gt; a.Foo)
      .Select(a =&gt; new {
          Id = a.Foo,
          Mean = a.GeoMean(b =&gt; b.Value)
      });  
  </code></pre>
  <p>I seem to have figure out I must use <code>a.AsQueryable().GeoMean()</code>, and an extension method looking something like this:</p>
  <pre class="lang-cs prettyprint-override"><code>public static double GeoMean&lt;T&gt;(this IQueryable&lt;T&gt; source, Expression&lt;Func&lt;T, double&gt;&gt; fn)
  {
      return Math.Exp(source.Average(i =&gt; Math.Log(fn(i))));
  }
  </code></pre>
  <p>However, since it's expected to return double it complains that <code>fn</code> is an <code>Expression</code>. If I change the return type to <code>Expression&lt;Func&lt;double&gt;&gt;</code> I've merely moved the problem to the <code>Select</code> in my query, so I probably need to do something to it, but what?</p>
  <p>Is this even possible? Should I just accept that I'll have to duplicate the code every time I need the calculation?</p>