문제

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 코드 내에서 실행하고 싶습니다.

엔티티 프레임 워크를 사용하고 기능 매핑으로 매핑하려고했지만 성공하지 못했습니다. 나는 간단한 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의 게시물이 웰코 커밋됩니다.

도움이 되었습니까?

해결책

그것은처럼 들린다 오른쪽 이 경우 엔티티 프레임 워크의 기능을 사용하여 .NET 함수를 정의하고 UDF에 매핑하는 것이지만 ado.net을 사용할 때 기대하는 결과를 얻지 못하는 이유를 알 수 있습니다. - 저장된 절차를 호출한다고 말하고 있지만 실제로 기능을 호출합니다.

이 시도:

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를 호출 할 수 있습니다. 이것은보다 일반적인 솔루션으로 유용 할 수 있습니다. 이것은 또한 철저히 테스트되지 않았습니다 ... Varchars에 문제가있을 것이라고 생각합니다.

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