2

I am trying to perform a dapper query like this:

string query = "select * from MyTable where someNumber in @Nums;";
...
connection.Query<ReturnObj>(query, new {Nums = nums})

And I am getting a MySql syntax error if nums is empty. It looks like Dapper changes the query to look like this: WHERE 1 = 0) so I am guessing it the left ( is missing, which is causing the syntax error. Yes, I realize I could just check if the collection is empty before executing the query, but I would rather not if I don't have to.

2
  • nums = numIds.ToReadOnlyCollection(), where numIds is an IEnumerable Commented Aug 16, 2012 at 23:05
  • It's more rather the fact that I think Dapper should handle a situation like this rather than me having to fix it's mistake. Commented Aug 16, 2012 at 23:19

1 Answer 1

3

This is a bug in Dapper where it creates a SQL statement that is invalid for MySQL Server 5.6 (and earlier).

Workarounds:

  • Upgrade to MySQL Server 5.7 (which accepts the SQL Dapper generates and returns the expected results)
  • As you said, check if the collection is empty before executing the query

A variant of checking if the collection is empty (that can be useful if you have a complex query, NOT IN, etc.):

  var numsSql = nums.Any() ? "@Nums" : "(select null)";
  var query = $"select * from MyTable where someNumber in {numsSql};";
  conn.Query(query, new { Nums });
Sign up to request clarification or add additional context in comments.

Comments

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.