title: How to call Scalar-valued function from LINQ to Entities server-side
body: <p>I have a Scalar-valued function in my DB:</p>
  
  <pre><code>ALTER FUNCTION [dbo].[fx_fooFunct]
    (@MyParam varchar(max))
  RETURNS varchar(max)
  AS
  BEGIN
    return @MyParam
  END
  </code></pre>
  
  <p>I want to call this function from a LINQ to Entities query and get the result into a variable:</p>
  
  <pre><code>let result = this.ObjectContext.ExecuteFunction&lt;string&gt;("SELECT dbo.fx_fooFunct(@MyParam)", new ObjectParameter("MyParam", "hello world")).FirstOrDefault()
  </code></pre>
  
  <p>But, when I execute the code, I get this error:</p>
  
  <blockquote>
    <p>LINQ to Entities does not recognize the method
    'System.Data.Objects.ObjectResult`1[System.String]
    ExecuteFunction[String](System.String,
    System.Data.Objects.ObjectParameter[])' method, and this method cannot
    be translated into a store expression.</p>
  </blockquote>
  
  <p>Other Info:</p>
  
  <p>This is part all of a query running on the server.<br>
  Returning all the data and using LINQ to Objects is not an option due to performance.<br></p>
  
  <p>I'm not sure that I have the return type of the <code>ExecuteFunction</code> correct, but I'm not sure what else it could be...
  What am I doing wrong?</p>
  
  <p><strong>Edit</strong><br>
  With the help of Ladislav Mrnka's answer, here is the solution:</p>
  
  <p>Create helper method exposing the SQL function:</p>
  
  <pre><code>public class CustomSqlFunctions
  {
      [EdmFunction("MyModel.Store", "fx_fooFunct")]
      public static string FooFunct(string myParam)
      {
          throw new NotSupportedException("Direct calls not supported");
      }
  } 
  </code></pre>
  
  <p>The LINQ should now read:</p>
  
  <pre><code>let result = CustomSqlFunctions.FooFunct("hello world")
  </code></pre>