Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

c# - Entity Framework - stored procedure return value

I am trying to get the return value of a stored procedure. Here is an example of such a stored procedure:

select
    Name,
    IsEnabled
from
    dbo.something
where
    ID = @ID

if @@rowcount = 0
    return 1    

return

This is a simple select. If 0 rows are found, my result set will be null, but I will still have a return value.

This is a bad example, as this is a select, so sure I could find if 0 rows were returned. However, on an Insert, delete, or other calls, we need this return value to know if there was a problem. I have been unable to find a way to get this return value. I can get output values, I can get result sets, but no return value.

I can get the return value if I call SQL manually, or even if I run a SqlCommand using the Entity Framework, but this is not what I want to do.

Has anyone ever been able to get the return value from a stored procedure using Entity Framework?

Thanks for the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...