Entity Framework - stored procedure return value

前端 未结 5 959
别那么骄傲
别那么骄傲 2020-11-28 11:15

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.somethi         


        
相关标签:
5条回答
  • 2020-11-28 11:55

    In order to get the interested result in EF, you should return a same structure (not 1 and Name, IsEnabled) In this query you should return '',0 for example instead of 1 in the if condition:

    select
        Name,
        IsEnabled
    from
        dbo.something
    where
        ID = @ID
    
    if @@rowcount = 0
        return '',0
    
    0 讨论(0)
  • 2020-11-28 11:56

    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

    0 讨论(0)
  • 2020-11-28 12:15

    No. Entity Framework doesn't have rich stored procedure support because its an ORM, not a SQL replacement.

    As you have already discovered, if you need to use less common (more advanced?) features of stored procedures, you'll have to use good old fashioned ADO.NET.

    0 讨论(0)
  • 2020-11-28 12:18

    I have been able to get the return value (and also output and input parameters) with Entity Framework 5 (but I think it works from version 4.x) using the code first approach. From your post I don't see what version of EF you are using and how you're doing your mapping; if you consider to use code-first approach here you can find my post with the solution:

    Get return value from stored procedure

    0 讨论(0)
  • 2020-11-28 12:19

    You must use the "Context.Database.SqlQuery",and specify the output type of the stored procedure

            var spReturnVaue = Context.Database.SqlQuery<Type>("[schema].YourSp").FirstOrDefault();
    
            int firstId = Context.Database.SqlQuery<int>("[dbo].GetFirstId").FirstOrDefault();
    
    0 讨论(0)
提交回复
热议问题