4

I am using this generic method:

protected IEnumerable<T> ExecuteSprocQuery<T>(string sproc, object objectParams)
{
    using (var conn = OpenConnection())
    {
    var list = conn.Query<T>(sproc, null, commandType: CommandType.StoredProcedure);
    return list;
    }
}

to invoke stored procedures like this:

ExecuteSprocQuery<SomePoco>("SomeSproc", new { P1 = p1, P2 = p2 }).ToList().FirstOrDefault();

I am trying to implement something similar for parameterised sql queries:

protected IEnumerable<T> ExecuteQuery<T>(string sqlString, object objectParams)
{
    using (var conn = OpenConnection())
    {
    var list = conn.Query<T>(sqlString, null, commandType: CommandType.Text);
    return list;
    }
}

but something like this throws an error:

ExecuteQuery<int?>("Select id from [dbo].[TableName] where [X] = @x ", new { @x  = 1}).FirstOrDefault();

Any ideas?

PS:

The error is:

Additional information: Must declare the scalar variable "@x".
2
  • Try to replace @x with x Commented Oct 20, 2014 at 13:09
  • 2
    You're not passing the objectParams into the Query call. Is that a typo? Commented Oct 20, 2014 at 13:15

1 Answer 1

4

It looks like you are never passing the params object to Query() inside your methods. Without the code for your SP it's hard to tell, but it might be accepting nulls as parameters and thus not failing, while raw SQL will most probably just crash.

var list = conn.Query<T>(sproc, objectParams, commandType: CommandType.StoredProcedure);

var list = conn.Query<T>(sqlString, objectParams, commandType: CommandType.Text);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It is Monday after all (-:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.