从存储过程中获取返回值

Dan*_*sco 48 c# stored-procedures return-value ef-code-first entity-framework-5

我正在使用Entity Framework 5和Code First方法.我需要从存储过程中读取返回值; 我已经在读取输出参数和发送输入参数,但我不知道如何读取返回值.

可能吗?

这是我用来调用存储过程的代码:

var outParam = new SqlParameter();
outParam.ParameterName = "@StatusLog";
outParam.SqlDbType = SqlDbType.NVarChar;
outParam.Size = 4000;
outParam.Direction = ParameterDirection.Output;

var code = new SqlParameter();
code.ParameterName = "@Code";
code.Direction = ParameterDirection.Input;
code.SqlDbType = SqlDbType.VarChar;
code.Size = 20;
code.Value = "123";

var data = _context.Database.SqlQuery<Item>("exec spItemData @Code, @StatusLog OUT", code, outParam);

var result = data.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

Dan*_*sco 46

我找到了!我可以使用必须以这种方式使用的输出参数来读取返回值:

// define a new output parameter
var returnCode = new SqlParameter();
returnCode.ParameterName = "@ReturnCode";
returnCode.SqlDbType = SqlDbType.Int;
returnCode.Direction = ParameterDirection.Output;

// assign the return code to the new output parameter and pass it to the sp
var data = _context.Database.SqlQuery<Item>("exec @ReturnCode = spItemData @Code, @StatusLog OUT", returnCode, code, outParam);
Run Code Online (Sandbox Code Playgroud)

  • 它根本没有意义,因为有一个ParameterDirection.ReturnValue.但是你的解决方案适合我.谢谢! (4认同)

Mar*_*rio 26

Daniele提供的解决方案对我不起作用,直到我从Diego Vega发现这篇博文后解释说:

在访问输出参数的值之前,您需要阅读整个结果(...)这就是存储过程的工作方式,而不是特定于此EF功能.

另外,在我的情况下,我没有返回一个实体,我只需执行存储过程,所以我Itemobjectin 替换_context.Database.SqlQuery<object>.

以下是示例代码:

var code = new SqlParameter("@Code", 1);

var returnCode = new SqlParameter("@ReturnCode", SqlDbType.Int);
returnCode.Direction = ParameterDirection.Output;

var outParam = new SqlParameter("@StatusLog", SqlDbType.Int);
outParam.Direction = ParameterDirection.Output;

var sql = "exec @ReturnCode = spSomeRoutine @Code, @StatusLog OUT";
var data = _context.Database.SqlQuery<object>(sql, returnCode, code, outParam);

// Read the results so that the output variables are accessible
var item = data.FirstOrDefault();

var returnCodeValue = (int)returnCode.Value;
var outParamValue = (int)outParam.Value;
Run Code Online (Sandbox Code Playgroud)

这是一个示例存储过程:

CREATE PROCEDURE [dbo].[spSomeRoutine]
    @Code Int,
    @StatusLog INT OUTPUT
AS
BEGIN
    SET @StatusLog = 5
    RETURN 10
END
Run Code Online (Sandbox Code Playgroud)

  • 我能够复制您的错误,所以是的,变量名很重要,但是在这种情况下,问题不在存储过程中,而是在SQL调用中,因此请确保在`“ exec @ReturnCode中指定了变量名= ...`与`var returnCode = new SqlParameter(“ @ ReturnCode”,SqlDbType.Int);中的一个匹配。 (2认同)

Kir*_*eed 11

在存储过程没有输出参数的情况下,我执行以下操作,有效地使一些Sql返回一个select语句;

var data = context.Database.SqlQuery<int>(@"declare @num int
exec  @num = myStoredProcThatReturnsInt 
select @num");

var result = data.First();
Run Code Online (Sandbox Code Playgroud)