Entity Framework – stored procedure return value

I guess support of stored procedure return values depends on version of Entity framework. Although directly returning value didn’t work for me I managed to get value using OUTPUT stored procedure parameter. Example:

USE [YOUR_DB_NAME]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[TestReturnValue]
    @InputValue int = 0,
    @Result int OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    SELECT @Result  = @InputValue
    RETURN(@InputValue);
END

This is test code:

void TestReturnValue()
{
    using (var db = new YourDBContext())
    {
        var result = new System.Data.Objects.ObjectParameter("Result", 0);
        Console.WriteLine("SP returned {0}", db.TestReturnValue(123, result));
        Console.WriteLine("Output param {0}", result.Value);
    }
}

And this is output:

SP returned -1
Output param 123

As you see directly returned value output some rubbish but OUTPUT parameters works!

This article provides general info on two ways of returning values from SP

Hope this helps

Leave a Comment