Check null for list parameter in Dapper
The id in @ids
is a pattern that is recognized by dapper and treated as an expansion - so depending on the number of items in your input ids
, this could become one of:
(1 = 0) -- empty sequence
(id = @ids_0) -- sequence with 1 element
(id in (@ids_0, @ids_1, ...)) -- sequence with multiple elements
Because of this, after the expansion, there is no @ids
parameter / variable - so @ids IS NULL
is not going to work. As such, I propose the best way to do this in your case is simply: don't add that part of the tsql. For example:
var sql = new StringBuilder("select * from Table1");
if(ids != null && ids.Any())
{
sql.Append(" where id in @ids");
}
var data = conn.Query<SomeType>(sb.ToString(), new { ids }).ToList();
where Id in @ids or 0=@listCount
and then
var data = conn.Query<SomeType>(sb.ToString(), new { ids, listCount=ids.Count }).ToList();