Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a value from a stored procedure to EF

I'm attempting to call a stored proc through EF and retrieve a return value from the stored proc. I've used this answer as a guide. Here is my stored proc:

CREATE PROCEDURE [dbo].[usp_test]
(
    @result int OUT
)
AS
BEGIN

--DO STUFF

SET @result = 0
END

Here is how I'm calling it from EF:

var status = new SqlParameter
{
    ParameterName = "result",
    DbType = DbType.Int32,
    Direction = ParameterDirection.Output 
};
var result = context.Database.SqlQuery<int>("EXEC usp_test @result", status);
var wasSuccessful = result.First() == 1;
if (!wasSuccessful)
{
    //DO STUFF
}

I'm getting this error message:

The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types

What am I doing wrong?

like image 701
im1dermike Avatar asked Oct 30 '22 09:10

im1dermike


2 Answers

Try select @result before end of procedure.

CREATE PROCEDURE [dbo].[usp_test]
(
    @result int OUT
)
AS
BEGIN

--DO STUFF

SET @result = 0
Select @result
END

Hope it works.

like image 165
Mojtaba Avatar answered Nov 15 '22 05:11

Mojtaba


I wanted to return the new id of an inserted row with a stored procedure. So I also made an OUTPUT parameter. In C# with EF6 I got it as following:

using System.Data.Entity.Core.Objects;
...
db = new myEntities1();
ObjectParameter returnId = new ObjectParameter("returnId", DbType.Int64);
db.postLogItem("New item.", returnId);
MessageBox.Show("Logitem added. New returnId: " + (int)returnId.Value);

The name of the variable in the stored procedure needs to match the one with calling the constructor of ObjectParameter.

CREATE PROCEDURE [dbo].[postLogItem]
    @description nvarchar(200),
    @returnId bigint OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO dbo.LogItem 
        (
            time,
            description
        )
        VALUES
        (
            GETDATE(),
            @description
        );

    SET @returnId = SCOPE_IDENTITY();
END
like image 32
Pete Avatar answered Nov 15 '22 05:11

Pete