如何使用Dapper获取存储过程的返回值?

时间:2017-05-24 14:27:18

标签: c# sql-server asp.net-mvc dapper data-access-layer

我在asp.net mvc 4项目中使用Dapper .net f / w 4.6.1使用sql server 2016 express

<packages>
  <package id="Dapper" version="1.50.2" targetFramework="net461" />
</packages> 

我有一个存储过程,它从2个表中删除,这些表应该是事务性的

ALTER PROCEDURE [dbo].[FeedbackDelete] @FeedbackID UNIQUEIDENTIFIER
AS 
    SET NOCOUNT OFF 
    SET XACT_ABORT ON  

BEGIN TRANSACTION
    DELETE
    FROM dbo.Document
    WHERE FeedbackId = @FeedbackID
    IF(@@ERROR != 0)
        BEGIN
            ROLLBACK TRANSACTION
            RETURN 1
        END

    DELETE
    FROM   [dbo].[Feedback]
    WHERE  [FeedbackID] = @FeedbackID
    IF(@@ERROR != 0 OR @@ROWCOUNT != 1)
        BEGIN
            ROLLBACK TRANSACTION
            RETURN 1
        END

COMMIT TRANSACTION
RETURN 0

我的repo方法使用像这样的短小精悍

public Response DeleteFeedback(Guid feedbackId)
        {
            string storedProcName = "FeedbackDelete";
            int returnValue = int.MinValue;
            using (var con = Connection)
            {
                con.Open();
                returnValue = con.Execute(storedProcName, new { feedbackId }, commandType: CommandType.StoredProcedure);
            }
            return Convert.ToInt32(returnValue) == 0 ? new Response(Code.Success, "Feedback successfully deleted") : new Response(Code.Failure, "There was an error deleting feedback");
        }

我得到的 returnValue 每次都是1,这是可以理解的,因为dapper会返回受影响的行数。

但是我想得到我的存储过程的return语句的值,以检查事务删除期间的错误(在我的情况下,成功为0,任何错误为1)

我如何实现这一目标?

使用裸机ado.net我曾经这样做并且有效

var returnValue = db.ExecuteScalar(storedProcName, new object[] { feedbackId });

使用dapper我尝试过con.ExecuteScalar,因为dapper元数据显示标量//返回://选择的第一个单元格

任何帮助将不胜感激?

以下是我需要使用Dapper执行的下一个步骤

ALTER PROCEDURE [dbo].[FeedbackUpdate] 
    @DocumentData VARBINARY(MAX),
    @DocumentName NVARCHAR(100),
    @FeedbackID UNIQUEIDENTIFIER,
    @FirstName NVARCHAR(100),
    @LastName NVARCHAR(100),
    @Notes NVARCHAR(MAX)
AS 
    SET NOCOUNT ON 
    SET XACT_ABORT ON  

    BEGIN TRAN

    UPDATE [dbo].[Feedback]
    SET    [FirstName] = @FirstName, [LastName] = @LastName, [Notes] = @Notes
    WHERE  [FeedbackID] = @FeedbackID
    IF(@@ERROR != 0 OR @@ROWCOUNT != 1)
        BEGIN
            ROLLBACK TRAN
            RETURN 1
        END

    IF DATALENGTH(@DocumentData) > 1
    BEGIN

            DELETE
            FROM   [dbo].[Document]
            WHERE  FeedbackId = @FeedbackId
            IF(@@ERROR != 0)
                BEGIN
                    ROLLBACK TRAN
                    RETURN 1
                END

            INSERT [dbo].[Document] (DocumentData,DocumentName,DocumentId,FeedbackId)
            VALUES(@DocumentData,@DocumentName,NEWID(),@FeedbackID)
            IF(@@ERROR != 0 OR @@ROWCOUNT != 1)
                BEGIN
                    ROLLBACK TRAN
                    RETURN 1
                END
        END

        COMMIT TRAN
        RETURN 0

3 个答案:

答案 0 :(得分:15)

您可以使用direction声明动态参数:ReturnValue 您也可以使用&#34;选择&#34;而不是&#34;返回&#34;并使用Query<T>扩展名。

create procedure sp_foo
    as
    begin
        return 99
    end

[Test]
public void TestStoredProcedure()
{
    using (var conn = new SqlConnection(@"Data Source=.\sqlexpress;Integrated Security=true; Initial Catalog=foo"))
    {
        var p = new DynamicParameters();
        p.Add("@foo", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

        conn.Execute("sp_foo", p, commandType: CommandType.StoredProcedure);

        var b = p.Get<int>("@foo");

        Assert.That(b, Is.EqualTo(99));
    }
}

答案 1 :(得分:1)

您必须使用Direction.ReturnValue

为存储过程定义SqlParameter

答案 2 :(得分:0)

csharp /服务器端

var result = conn.QuerySingle<int>(
                "sp_test",
                new
                {
                    param1 = "something"
                },
                commandType: CommandType.StoredProcedure
            );

和存储过程

create procedure sp_test(varchar(255) param1)
    as
    begin
        if param1 = "bla bla" then -- or some other validation against param1
           select -1;
        end if;

        -- do something

        select 1; -- if reached this point everything is fine
    end

使用mysql 5.7.1的批准的解决方案不适用于我。所以我只是在这里发布我的解决方案。示例的结果将为1,如果param1更改为something

,则结果为-1