Dapper - must declare scalar variable

Cenk 1,001 Reputation points
2023-05-17T06:38:47.7466667+00:00

Hi guys,

I am having trouble using Dapper. Getting must declare scalar variable @orderNo error.

How can I fix this?

private async Task GetDataForPdf(string orderNo)
 {
            var connString = _configuration["ConnectionStrings:Production"];
            await using var sqlConnection = new SqlConnection(connString);
            sqlConnection.Open();

            await using var command = new SqlCommand { Connection = sqlConnection };
            const string sql =
                @"select od.quantity, od.productCode, od.productName, od.price, od.quantity * od.price As Total, o.orderTotalPrice, o.orderDate, o.orderBy,o.email
                    from Orders o
                    inner join OrderDetail  od ON od.orderId = o.id
                    where od.status = 2 and o.orderNo = @orderNo";
            

            command.Parameters.Add(new SqlParameter("orderNo", orderNo));
            try
            {
                //Dapper
                var results = await sqlConnection
                    .QueryAsync<PdfDto>(sql);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            

            //generate Pdf
            //SendEmailWithColumns(results);


        }

Thank you.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,936 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,421 Reputation points
    2023-05-17T09:08:24.49+00:00

    One of the benefits of Dapper is less code, here there is zero need for a SqlCommand.

    Simple example where parameters is how to set the parameter for @id.

    var sql = "SELECT id, Photo FROM dbo.Pictures1 WHERE dbo.Pictures1.id = @id";
    
    using var cn = new SqlConnection(ConnectionString());
    var parameters = new { id = identifier };
    var container = cn.QueryFirstOrDefault<ImageContainer>(sql, parameters);
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 44,736 Reputation points
    2023-05-17T07:28:44.5+00:00

    You assign the parameter "orderno" to the SqlCommand "command"; but you don't use the command anywhere, you work dirctly with SqlConnection and the SQL statement with the parameter name.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.