I am attempting to parameterize multiple values that are going into my query, but keep getting errors. This is what I am currently working on, in which I am getting a "must declare the scalar variable" error on the userClientIds parameter. Can someone help me figure out what I am missing.
public async Task<IEnumerable<SharedUser>> GetUsersForSharing(Guid userId, Guid
templateId, string? searchedEmpName, string? searchedEmpNumber)
{
// this is a list of ints, which will need passed into the WHERE IN clause below
var userClientIds = userClients.Select(client => client.ClientId).ToList();
var sql = $@"SELECT DISTINCT
UserId,
ClientId,
FullName,
EmployeeNumber
FROM dbo.ClientUser
WHERE
UserId <> @UserId
AND ClientId in (
@userClientIds
)";
if(searchedEmpName != null)
{
sql += $@"AND FullName LIKE '%@searchedEmpName%'";
}
if(searchedEmpNumber != null)
{
sql += $@"AND EmployeeNumber LIKE '%@searchedEmpNumber%'";
}
using(var conn = _connectionFactory.GetDbConnection())
{
var parameters = new DynamicParameters();
parameters.Add("@userId", userId.ToString());
parameters.Add("@userClientIds", new[] { userClientIds });
parameters.Add("@searchedEmpName", searchedEmpName);
parameters.Add("@searchedEmpNumber", searchedEmpNumber);
conn.Open();
var result = await conn.QueryAsync<SharedUser>(sql, new { parameters });
return result;
}
}
userClientIdsis already an array does it (new[] { userClientIds }) not create nested array? Would you try to with onlyuserClientIds.new { parameters },parametersis already an object.AND ClientId in @userClientIds& add parameter asparameters.Add("@userClientIds", userClientIds);.parameters.Add("@userClientIds, new[] { userClientIds });. The variableuserClientIdsis already a collection (a list). You are passing an array of lists. Try makinguserClientIdsan array instead of a list and just pass that insql += $@"AND FullName LIKE '%@searchedEmpName%'";will not replace your parameter value since it will be not be consider as variable because it is wrapped within single quotes.