System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@Referans".'

System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@Referans".'

我正在尝试使用 Dapper 执行存储过程。我收到一个错误:

System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@Referans".'

这是我的代码:

var dosyaDetaySql = @"exec TurkmenBeyannameDetaylar @Referans";
var dosyaDetay = conn.Query<TurkmenBeyannemeSabitleriDetay>(dosyaDetaySql, new { dosyaResult.REF }).ToList();

我试过 @"exec TurkmenBeyannameDetaylar '@Referans'"; 但这也不起作用。怎样修改才能让存储过程成功执行?

您传递的查询语法有误。它应该是这样的:

var dosyaDetaySql = "exec TurkmenBeyannameDetaylar @Referans";
var dosyaDetay = conn
     .Query<TurkmenBeyannemeSabitleriDetay>(dosyaDetaySql, new { Referans = dosyaResult.REF})
     .ToList();

顺便说一句,您可能会遇到以这种方式声明的 DynamicParameters 的问题。相反,更容易恕我直言,写成:

var parameters = new DynamicParameters();
parameters.Add("@Referans", dosyaResult.REF);

var dosyaDetaySql = @"exec TurkmenBeyannameDetaylar @Referans";
var dosyaDetay = conn
    .Query<TurkmenBeyannemeSabitleriDetay>(dosyaDetaySql, parameters)
    .ToList();

PS: returns 参数名错误的时候也会报错。确保 SP 参数名称 (@Referans) 在添加参数的代码中匹配。

编辑:添加下面的示例只是为了解释我添加 DynamicParameters 的原因。您不需要它,但在某些情况下您可能会发现它更容易。自己决定。

void Main()
{
    var query = @"EXEC dbo.CustOrdersDetail @ID";
    var parameters = new {ID=10280};
    var result = GetResults<dynamic>(query, parameters);
    foreach (var order in result)
    {
        Console.WriteLine($"{order.ProductName}, {order.UnitPrice}, {order.Discount}, {order.ExtendedPrice}");
    }

    Console.WriteLine("=====================================");
    var parameters2 = new DynamicParameters();
    //parameters2.AddDynamicParams(new {ID=10280}); // not easy for everyone to write - I don't know why I think that way
    parameters2.Add("@ID", 10280, DbType.Int32);

    var result2 = GetResults_2<dynamic>(query, parameters2);
    foreach (var order in result2)
    {
        Console.WriteLine($"{order.ProductName}, {order.UnitPrice}, {order.Discount}, {order.ExtendedPrice}");
    }
}

private static IEnumerable<T> GetResults<T>(string query, object parameters = null)
{
    using (IDbConnection db = new SqlConnection(@"Server=.\SQLExpress2012;Database=Northwind;Trusted_Connection=true"))
    {
        return db.Query<T>(query, parameters);
    }
}

public static IEnumerable<T> GetResults_2<T>(string query, DynamicParameters parameters=null)
{
    using (IDbConnection db = new SqlConnection(@"Server=.\SQLExpress2012;Database=Northwind;Trusted_Connection=true"))
    {
        return db.Query<T>(query, parameters);
    }
}

两者的结果相同:

Guaraná Fantástica, 3.6000, 0, 43.2000
Pâté chinois, 19.2000, 0, 384.0000
Rhönbräu Klosterbier, 6.2000, 0, 186.0000
=====================================
Guaraná Fantástica, 3.6000, 0, 43.2000
Pâté chinois, 19.2000, 0, 384.0000
Rhönbräu Klosterbier, 6.2000, 0, 186.0000