Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get return value from stored procedure using ExecuteSqlCommand (using Entity Framework)

I have code that looks like this:

int retval = databaseContext.Database.ExecuteSqlCommand(command, sqlParameters.ToArray());

Where databaseContext is of type System.Data.Entity.DbContext

I want to use the return value to know whether or not the stored procedure ran successfuly. Based on the documentation ExecuteSqlCommand should return the result of the stored procedure.

However, The command always returns -1 to retval, no matter what I set the stored procedure to do. I've tried returning various integers and even calling RAISERROR in the stored procedure, but the return value is consistently -1.

Here are two stored procs I tried but they both returned -1 and did not give any indication of whether it ran successfully or not:

CREATE PROCEDURE [dbo].[myproc]
AS
BEGIN
      RAISERROR ('You fail', -- Message text.
                       0, -- Severity - operation failed.
                       500-- State.
                       );
END
GO

CREATE PROCEDURE [dbo].[myproc]
AS
BEGIN
      RETURN 1
END
GO

Any idea what I'm doing wrong here?

like image 256
Zain Rizvi Avatar asked Nov 17 '15 00:11

Zain Rizvi


People also ask

How can we return a value in stored procedure?

The RETURN statement is used to unconditionally and immediately terminate an SQL procedure by returning the flow of control to the caller of the stored procedure. It is mandatory that when the RETURN statement is executed that it return an integer value. If the return value is not provided, the default is 0.

Can we use Entity Framework with stored procedure?

You can use stored procedures either to get the data or to add/update/delete the records for one or multiple database tables. EF API creates a function instead of an entity in EDM for each stored procedure and User-Defined Function (UDF) in the target database.


1 Answers

Based on DavidG's comment:

ExecuteSqlCommand only returns values if it's the result of a select statement.

If you want the return value of a stored procedure (like shown in the question), then you have to use the EXEC @ReturnValue = [StoredProc] @param1 ... method as described in this SO answer.

like image 133
Zain Rizvi Avatar answered Nov 14 '22 21:11

Zain Rizvi