【问题标题】:Stored procedure returning value of 1 in Entity Framework, and correct value in SSMS存储过程在实体框架中返回值 1,在 SSMS 中返回正确值
【发布时间】:2016-09-06 19:47:25
【问题描述】:

在使用 Entity Framework 的测试应用程序中,我从以下存储过程中获得了返回值 1 的值。在 SQL Server Management Studio 中,我根据身份返回正确的值,例如 3345

存储过程:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER Procedure [dbo].[sp_testCredentials]
    @mainPiece int,
    @textInfo varchar(25),
    @state int,
    @UserName varchar(20)
AS
    DECLARE @returnVal AS INT 

    IF (@mainPiece = 0)
    BEGIN
        INSERT INTO userList (@textInfo, @state, enteredUser, lastUpdatedUser) 
        VALUES (@textInfo, @state, @UserName, @UserName)

        SET @returnVal =   @@identity  
    END

    RETURN @returnVal

Entity Framework C# 中的存储过程调用

public virtual int sp_testCredentials(Nullable<int> mainPiece, string textInfo, Nullable<int> state, string UserName)
{
    var mainParameter = mainPiece.HasValue ?
        new ObjectParameter("mainPiece ", mainPiece ) :
        new ObjectParameter("mainPiece ", typeof(int));

    var textParameter = textInfo  != null ?
        new ObjectParameter("textInfo ", textInfo ) :
        new ObjectParameter("textInfo" , typeof(string));

    var stateParameter = state.HasValue ?
        new ObjectParameter("state", state) :
        new ObjectParameter("state", typeof(int));

    var nameParameter = UserName  != null ?
        new ObjectParameter("UserName ", UserName) :
        new ObjectParameter("UserName ", typeof(string));

    var test = ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction
                       ("sp_testCredentials", mainParameter, 
                         textParameter, stateParameter, nameParameter);
    return test;
}

【问题讨论】:

标签: sql-server entity-framework visual-studio stored-procedures


【解决方案1】:

请参阅MSDN definition 中的ExecuteFunction

执行数据中定义的存储过程或函数 来源并在概念模型中表达; 放弃任何结果 从函数返回;并返回受影响的行数 执行。

您必须使用ExecuteStoreQuery 才能在实体框架中检索您的存储过程输出。

例如,

context.ExecuteStoreQuery<Product>("select * from Products where pid = {0}", 1);
context.ExecuteStoreQuery<Product>("select * from Products where pid = @p0", 
                                   new SqlParameter { ParameterName = "p0", Value = 1 });

【讨论】:

    猜你喜欢
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多