title: Calling DB Function with Entity Framework 6
body: <p>I followed these instructions to add a scalar function into my Entity Framework 6 data model.
  <a href="https://stackoverflow.com/questions/12481868/how-to-use-scalar-valued-function-with-linq-to-entity">How to use scalar-valued function with linq to entity?</a></p>
  
  <p>However, I'm not able to call the function within a LINQ query, although calling the method directly on the DataContext works.</p>
  
  <pre><code>using (Entities context = new Entities()) {
      // This works.
      var Test1 = context.fn_GetRatingValue(8, 9, 0).FirstOrDefault();
      // This doesn't work.
      var Test2 = (from r in context.MediaRatings
                  select context.fn_GetRatingValue(r.Height, r.Depth, 0)).ToList();
  }
  </code></pre>
  
  <p>The second query throws this error.</p>
  
  <pre><code>LINQ to Entities does not recognize the method 'System.Data.Entity.Core.Objects.ObjectResult`1[System.Nullable`1[System.Single]] fn_GetRatingValue(System.Nullable`1[System.Single], System.Nullable`1[System.Single], System.Nullable`1[System.Single])' method, and this method cannot be translated into a store expression.
  </code></pre>
  
  <p>Also, the designer is giving me this warning</p>
  
  <pre><code>Error 6046: Unable to generate function import return type of the store function 'fn_GetRatingValue'. The store function will be ignored and the function import will not be generated.
  </code></pre>
  
  <p>What am I doing wrong? How can I call the database function within a LINQ query?</p>
  
  <p>Also, if the query code sometimes gets executed against the database and sometimes in-memory, is there a way to call the function in a way that works in both cases? I have a C# version of the same function.</p>
  
  <p>Thanks</p>
  
  <p>Edit: Here's the function I'm trying to use.</p>
  
  <pre><code>public float? GetValue(float? Height, float? Depth, float ratio) {
      if (Height != null || Depth != null) {
          float HeightCalc = Height ?? Depth.Value;
          float DepthCalc = Depth ?? Height.Value;
          if (ratio &lt; 0)
              DepthCalc = DepthCalc + (HeightCalc - DepthCalc) * -ratio;
          else if (ratio &gt; 0)
              HeightCalc = HeightCalc + (DepthCalc - HeightCalc) * ratio;
          return (float)Math.Round(HeightCalc * DepthCalc * .12, 1);
      } else
          return null;
  }
  </code></pre>
  
  <p>It can also be written in one line like this. This line could be copy/pasted everywhere I need to use it but that would produce very ugly code, although that could work. I'd rather keep it as a function.</p>
  
  <pre><code>return (float)Math.Round(
      (Height.HasValue ? Height.Value + (ratio &gt; 0 ? ((Depth ?? Height.Value) - Height.Value) * ratio : 0) : Depth.Value) *
      (Depth.HasValue ? Depth.Value + (ratio &lt; 0 ? ((Height ?? Depth.Value) - Depth.Value) * -ratio : 0) : Height.Value)
      * .12, 1);
  </code></pre>