title: How to use SQL user defined functions in .NET?
body: <p>I created a scalar function in the DB</p>
  
  <pre><code>SET ANSI_NULLS ON
  GO
  SET QUOTED_IDENTIFIER ON
  GO
  ALTER FUNCTION [dbo].[fn_GetUserId_Username]
      (
      @Username varchar(32)
      )
  RETURNS int
  AS
      BEGIN
      DECLARE @UserId int
      SELECT @UserId = UserId FROM [User] WHERE Username = @Username
      RETURN @UserId
      END
  </code></pre>
  
  <p>Now I want to run it within my .NET C# or VB.NET code.</p>
  
  <p>I use Entity Framework, I tried to map it with function mapping and I did not success.
  i don't care to do it with simple DbCommand, the problem is that I get no results (the function exists in the Entities class):</p>
  
  <pre><code>public int GetUserIdByUsername(string username)
  {
      EntityConnection connection = (EntityConnection)Connection;            
      DbCommand com = connection.StoreConnection.CreateCommand();
      com.CommandText = "fn_GetUserId_Username";
      com.CommandType = CommandType.StoredProcedure;
      com.Parameters.Add(new SqlParameter("Username", username));
      if (com.Connection.State == ConnectionState.Closed) com.Connection.Open();
      try
      {
          var result = com.ExecuteScalar(); //always null
      }
      catch (Exception e)
      { 
      }
      return result;
  }
  </code></pre>
  
  <p>Is there any solution?
  Posts in either C# or VB.NET will be welcommed.</p>