title: Best practice calling scalar functions with Entity Framework Core (2.1)
body: <p>I often need to call scalar functions that are defined on a SQL Server from my web applications (ASP.NET Core / EF Core). Since these functions are just simple helper functions and I also use a lot of them I use a general pattern for calling these scalar functions - with the help of the new query types available from EF Core 2.1.
  Since I am relatively new to EF Core my question is if this pattern might cause problems and/or if there is a better solution or best practice for calling scalar functions. The solution works and I cannot observe any problems so far but for example I wondered if using the same query type for different functions might lead to unexpected values or weird behaviour due to caching/tracking behaviour, etc. within EF Core - it's more of a gut feeling.</p>
  <p>So here's the pattern:
  Instead of defining different entity types for every single scalar function I simply define one generic type:</p>
  <pre><code>public class PrimitiveDto&lt;T&gt;
  {
      public T Value { get; set; }
  }
  </code></pre>
  <p>In my context class I register these types for every return type I expect from the scalar functions I want to use - so for all scalar functions returning 'int' the context class would have one additional entry like this:</p>
  <pre><code>public virtual DbQuery&lt;PrimitiveDto&lt;int&gt;&gt; BasicIntDto { get; set; }
  </code></pre>
  <p>For EF Core &gt;= 3 it is:</p>
  <pre><code>public virtual DbSet&lt;PrimitiveDto&lt;int&gt;&gt; BasicIntDto { get; set; }
  </code></pre>
  <p>In every part of the application where I want to call a scalar function returning 'int' I simply use the same following pattern:</p>
  <pre><code>context.BasicIntDto.FromSql(&quot;SELECT &lt;FUNCTION&gt; AS Value&quot;)
  </code></pre>
  <p>By using this pattern I can call any number of functions the same way without defining additional types or extending the context class.</p>
  <p>Please let me know if I could run into a trap through this pattern. Thank you very much.</p>