执行应返回int的存储过程

时间:2018-10-24 09:43:00

标签: stored-procedures entity-framework-6

我有一个存储过程,该过程需要几个输入参数并返回一个整数:

CREATE procedure [dbo].[HB_ValidateLogin_HitAlacarte]
(
    @Login nvarchar(50),
    @Pwd nvarchar(50),
    @Vat int, 
    @Page  nvarchar(50)
)
as
Begin
    return -3 --- too many Badlogins 
End

我使用Entity Framework将此存储过程称为:

try
{
    string sqlQuery = "exec [dbo].[HB_ValidateLogin_HitAlacarte] @Login, @Pwd, @Vat, @Page";

    var outParam = new SqlParameter();
    outParam.ParameterName = "@return_value";
    outParam.SqlDbType = System.Data.SqlDbType.BigInt;
    outParam.Direction = System.Data.ParameterDirection.Output;

    SqlParameter[] sqlParams = new SqlParameter[]
    {
        new SqlParameter { ParameterName = "@Login",  Value =initRequest.Login, Direction = System.Data.ParameterDirection.Input},
        new SqlParameter { ParameterName = "@Pwd",  Value =initRequest.Pwd, Direction = System.Data.ParameterDirection.Input },
        new SqlParameter { ParameterName = "@Vat",  Value =initRequest.VatNumber, Direction = System.Data.ParameterDirection.Input},
        new SqlParameter { ParameterName = "@Page",  Value =initRequest.Page, Direction = System.Data.ParameterDirection.Input},
        outParam
    };

    using (xmlALaCarteContext)
    {
        List<List<int>> result = xmlALaCarteContext.Database.SqlQuery<List<int>>(sqlQuery, sqlParams).ToList();
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    Console.WriteLine(ex.StackTrace);
    Console.ReadLine();
}

但是,当我运行代码时,我从未得到-3。我的outParam始终为null。我究竟做错了什么?我正在使用EntityFramework 6.0.0.0版

1 个答案:

答案 0 :(得分:1)

您需要在存储过程中将@return_value声明为OUTPUT参数,然后进行设置而不是调用RETURN

CREATE procedure [dbo].[HB_ValidateLogin_HitAlacarte] (
    @Login nvarchar(50),
    @Pwd nvarchar(50),
    @Vat int, 
    @Page  nvarchar(50),
    @return_value int OUTPUT
)

或更改您的exec语句,使其处理返回值,但我不确定与您的框架配合使用的语法正确,但类似

string sqlQuery = "exec @return_value =[dbo].[HB_ValidateLogin_HitAlacarte]..."