How do I use 'Where In' in Dapper

我只是一个虾纸丫 提交于 2019-12-03 04:36:24

To do what is needed here, dapper needs to alter the SQL on the fly - so it needs to be really sure that it is doing the right thing. The regular valid SQL syntax includes parenthesis:

WHERE StringId IN (@str)

To disambiguate from this, the voodoo dapper syntax omits the parenthesis:

WHERE StringId IN @str

If it detects this, it looks for a parameter called str, and expands it, to one of:

WHERE 1=0 -- if no values
WHERE StringId = @str -- if exactly one value
WHERE StringId IN (@str0, @str1, ...) -- if more than one value

But short version: remove the parenthesis.

user1856792

I want to add an important note if you are interested in being able to handle an empty list, aka make the IN clause optional. I did this by adding a property to contain the count such as public int InClauseCount => InClauseList?.Length ?? 0;

Then use the count within the sql like this...

Select field1, field2
from Table1
where (some condition)
AND (@InClauseCount = 0 OR field1 IN @InClauseList)

I hope this can help someone out there. I spent a little too long trying to solve this, partially because I'm new to Dapper.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!