Search code examples
c#stored-proceduresasp.net-coredapper

Using Dapper by stored procedure


I am working on asp.net core by using dapper ORM.I want to execute stored procedure in dapper and get the result in boolean value.How i can achieve this?

Actually, In stored procedure , i am returning 0 or 1,but when response come back in code, then the result have -1, i am confused, i am returning just 0 or 1.

 using (var connection = new SqlConnection(connectionString))
                {
                    // Create User Connection
                    var queryParameters1 = new DynamicParameters();
                    queryParameters1.Add("@ConnectionId", connectionId);
                    queryParameters1.Add("@UserTokenId", tokenResult?.Id);
                    response = await connection.ExecuteAsync(
                        "Proc_CreateUserConnection",
                        queryParameters1,
                        commandType: CommandType.StoredProcedure);
                }

I want to get the stored procedure output in boolean value or in the form of 0 or 1.


Solution

  • I would just like to expand on this a little.

    In this instance, you are returning a bool value which means its a single result. The best way to capture single results is using a scalar. This will ensure that only one value is returned and accessible by our code (as Deepankshee and others have already mentioned).

    You should ensure that you issue a select command which will only ever return one result (otherwise it will fail) at the end of your stored procedure.

    Then in your c# code you need to call:

    var result = await conn.ExecuteScalarAsync<T>("Your procedure", new { arguments },
        commandType: CommandType.StoredProcedure);
    

    Please note as well that you should await on this so we don't block the thread.