質問

私はDBにスカラー関数を作成しました。

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

今、私は私の.NET C#またはVB.NETのコード内でそれを実行したい。

私は、Entity Frameworkを使用する、私は関数マッピングでそれをマップしようとしたと私は成功しませんでした。 私はシンプルされたDbCommandでそれを行うには気にしない、問題は、私は(関数は、エンティティクラスに存在する)は結果を得るということです。

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;
}

任意の解決策はありますか? C#やVB.NETのいずれかでの投稿はwelcommedされます。

役に立ちましたか?

解決

これは、この場合には、の右のの方法のように聞こえる「.NET関数を定義して、UDFにそれをマップするために、エンティティフレームワークの機能を使用することですが、私はあなたがドンなぜ私が見ると思いますあなたがそれを行うにはADO.NETを使用するときtはあなたが期待する結果を得る - あなたは、ストアドプロシージャを呼び出していることを言っているが、あなたは本当に機能を呼び出しています。

これを試してください:

public int GetUserIdByUsername(string username)
{
    EntityConnection connection = (EntityConnection)Connection;            
    DbCommand com = connection.StoreConnection.CreateCommand();
    com.CommandText = "select dbo.fn_GetUserId_Username(@Username)";
    com.CommandType = CommandType.Text;
    com.Parameters.Add(new SqlParameter("@Username", username));
    if (com.Connection.State == ConnectionState.Closed) com.Connection.Open();
    try
    {
        var result = com.ExecuteScalar(); // should properly get your value
        return (int)result;
    }
    catch (Exception e)
    {
        // either put some exception-handling code here or remove the catch 
        //   block and let the exception bubble out 
    }
}

他のヒント

これは、上記の答えに非常に似ていますが、以下のコードを使用すると、任意の数のパラメータと任意の戻り値の型でUDFを呼び出すことができます。これは、より一般的な解決策として有用であるかもしれません。これも徹底的にテストされていませんが...私はそれがVARCHARが持ついくつかの問題を持っているだろうと思います。

public class MyDBAccess
{
    private SqlConnection sqlConnection = new SqlConnection("databaseconnectionstring");

    public int GetUserIdByUsername(string username)
    {
        int userID = CallUDF<int>("dbo.fn_GetUserId_Username", new SqlParameter("@Username", username));
        return userID;
    }

    internal static T1 CallUDF<T1>(string strUDFName, params SqlParameter[] aspParameters)
    {
        using (SqlConnection scnConnection = sqlConnection)
        using (SqlCommand scmdCommand = new SqlCommand(strUDFName, scnConnection))
        {
            scmdCommand.CommandType = CommandType.StoredProcedure;

            scmdCommand.Parameters.Add("@ReturnValue", TypeToSqlDbType<T1>()).Direction = ParameterDirection.ReturnValue;
            scmdCommand.Parameters.AddRange(aspParameters);

            scmdCommand.ExecuteScalar();

            return (T1)scmdCommand.Parameters["@ReturnValue"].Value;
        }
    }

    private SqlDbType TypeToSqlDbType<T1>()
    {
        if (typeof(T1) == typeof(bool))
        {
            return SqlDbType.Bit;
        }
        else if (typeof(T1) == typeof(int))
        {
            return SqlDbType.Int;
        }
        //
        // ... add more types here
        //
        else
        {
            throw new ArgumentException("No mapping from type T1 to a SQL data type defined.");
        }
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top