C# Dapper query using WHERE IN

c# dapper

Question

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.

Accepted Answer

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 });



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why