从存储过程中获取返回值 - LINQ

时间:2017-12-04 12:16:59

标签: c# sql-server entity-framework

我想使用LINQ,EF获取存储过程中的返回值。我见过使用T-SQL的解决方案,但该方法无法解决问题。我需要用LINQ来解决它。

返回0我想根据结果取1和-1

存储过程:

ALTER PROCEDURE [dbo].[Login]
    @inTcNu CHAR(11),
    @inPass NVARCHAR(MAX),
    @inIP NVARCHAR(40),
    @rolNu TINYINT OUTPUT,
    @kulNu INT OUTPUT
AS
BEGIN
    SELECT @kulNu = kullaniciID, @rolNu = rolID 
    FROM Kullanici WITH(NOLOCK) 
    WHERE tcNumarasi = @inTcNu AND parola = @inPass;

    IF @rolNu >= 0 AND @kulNu >= 0
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 1);

        RETURN 1;
    END
    ELSE
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 0);

        RETURN 0;
    END

    RETURN -1;
END

C#,LINQ,EF

using (var ctx = new ktdbEntities())
{
    var IP = networkUtils.GetIP();
    var rolNu = new ObjectParameter("rolNu", typeof(int));
    var kulNu = new ObjectParameter("kulNu", typeof(int));

    var output = ctx.Login(model.tcNumarasi, model.parola, IP, rolNu, kulNu);

    object value1 = rolNu.Value;
    object value2 = kulNu.Value;
}

1 个答案:

答案 0 :(得分:0)

您无法像这样从存储过程返回值。您可以传递输出参数来实现它。

首先我像这样修改你的sp;

ALTER PROCEDURE [dbo].[Login]
    @inTcNu CHAR(11),
    @inPass NVARCHAR(MAX),
    @inIP NVARCHAR(40),
    @rolNu TINYINT OUTPUT,
    @kulNu INT OUTPUT,
    @result INT OUTPUT
AS
BEGIN
    SELECT @kulNu = kullaniciID, @rolNu = rolID 
    FROM Kullanici WITH(NOLOCK) 
    WHERE tcNumarasi = @inTcNu AND parola = @inPass;

    IF @rolNu >= 0 AND @kulNu >= 0
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 1);

        set @result = 1;
    END
    ELSE
    BEGIN
        INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
        VALUES (@inTcNu, @inIP, @inPass, GETDATE(), 0);

        set @result = 0;
    END

    set @result = -1;
END

然后我看不到ctx.Login方法,但我假设您正在其中执行存储过程。

using (var ctx = new ktdbEntities())
{
    var IP = networkUtils.GetIP();
    var rolNu = new ObjectParameter("rolNu", typeof(int));
    var kulNu = new ObjectParameter("kulNu", typeof(int));
    var resultParam = new ObjectParameter("result", typeof(int));

    var output = ctx.Login(model.tcNumarasi, model.parola, IP, rolNu, kulNu,resultParam);

    object value1 = rolNu.Value;
    object value2 = kulNu.Value;
    object result = resultParam.Value; //Get output value
}