如何在 ASP.NET Core 中的参数化方法中声明标量变量?

问题描述 投票:0回答:1

我想通过使用参数化方法获取值,但我收到此错误“必须声明标量变量@Category”。我不知道在下面的代码中在哪里以及如何声明标量变量。

查看我尝试过的代码

  ` [Route("TotalValue")]
    [HttpGet]
    public decimal TotalValue()
    {
        var query = "Select * from OrderDetail where Category = @Category";
        string sqlDataSource = _configuration.GetConnectionString("DefaultConnection");
        decimal total = 0;

        using (SqlConnection con = new SqlConnection(sqlDataSource))
        {
            con.Open();
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.Read())
                    {
                        total = dr.GetDecimal(0); 
                    }
                }
            }
            con.Close();
        }

        return total;
    }`
asp.net-core sql-server-2014-express
1个回答
0
投票

你就快到了。

创建命令后,将@Category参数添加到命令的参数集合中:

[Route("TotalValue")]
[HttpGet]
public decimal TotalValue()
{
    var query = "Select * from OrderDetail where Category = @Category";
    string sqlDataSource = _configuration.GetConnectionString("DefaultConnection");
    decimal total = 0;

    // If a string (amend for other data type)
    string categoryToFind = "My Category To Search For";

    using (SqlConnection con = new SqlConnection(sqlDataSource))
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            cmd.Parameters.AddWithValue("@Category", categoryToFind);

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    total = dr.GetDecimal(0); 
                }
            }
        }
        con.Close();
    }

    return total;
}
© www.soinside.com 2019 - 2024. All rights reserved.