Search code examples
c#stored-proceduresef-code-firstentity-framework-5return-value

Get return value from stored procedure


I'm using Entity Framework 5 with the Code First approach. I need to read the return value from a stored procedure; I am already reading output parameters and sending input parameters, but I don't know how to read the return value.

Is it possible?

Here is the code that I use to call the stored procedure:

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();

Solution

  • I found it! I can read the return value with an output parameter that has to be used in this way:

    // 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);