Search code examples
sql-serverdapper

Dapper System.Data.SqlClient.SqlException: 'Must declare the scalar variable


I'm attempting to query for a specific record with an ID and am declaring the value of the ID but am still getting an error.

First I make the call to the db function:

specificEntity = await _db_FinancialEntityDb.GetFinancialEntity(id);

Then:

public Task<FinancialEntity_Model> GetFinancialEntity(int financialEntityID)
{
        string sql = @"select   fe.Id, 
                                fe.EntityTypeID, 
                                fe.Balance, 
                                fe.InterestRate, 
                                fe.OpenDate, 
                                fe.MinimumPayment, 
                                fe.APY, 
                                fe.EntityName, 
                                fe.InitialAmount, 
                                fet.EntityType 
                        from dbo.Financial_Entity fe 
                            left outer join Financial_Entity_Type fet on fe.EntityTypeID = fet.Id 
                        where fe.Id = @financialEntityID";
        
    return _db.LoadDataObject<FinancialEntity_Model, dynamic>(sql, new { Id = financialEntityID });
}

And I'm using QueryFirstAsync:

var data = await connection.QueryFirstAsync<T>(sql, parameters);

But I keep getting this error:

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

Is QueryFirstAsync the problem?


Solution

  • @financialEntityID should be @Id since that's the name you're passing to Dapper.

    When you pass parameters as an anonymous type the property names should match the parameter names. eg

    new { Id = financialEntityID }

    would bind a parameter called @Id with the value of financialEntityID.