我尝试在Dapper中使用带有WHERE IN
子句的IEnumerable<string>
已经有一段时间了,但没有成功。
在文档中,它确实说支持在WHERE IN
中使用IEnumerable<int>
,但我甚至不能让它工作。
Dapper allow you to pass in IEnumerable and will automatically parameterize your query.
我一直收到的错误消息是Sql语法错误。Incorrect syntax near ','.
我已经整理了一些测试代码,我希望这些代码能够演示我想要实现的目标。
string connString = "Server=*.*.*.*;Database=*;User Id=*;Password=*;";
string sqlStringIn = @"SELECT StringText FROM
(SELECT 1 ID, 'A' StringID, 'This is a test' StringText
UNION SELECT 2 ID, 'B' StringID, 'Another test' StringText
UNION SELECT 3 ID, 'C' StringID, 'And another' StringText
UNION SELECT 4 ID, 'D' StringID, 'and again' StringText
UNION SELECT 5 ID, 'E' StringID, 'yet again' StringText) data
WHERE StringId IN (@str)";
string sqlIntegerIn = @"SELECT StringText FROM
(SELECT 1 ID, 'A' StringID, 'This is a test' StringText
UNION SELECT 2 ID, 'B' StringID, 'Another test' StringText
UNION SELECT 3 ID, 'C' StringID, 'And another' StringText
UNION SELECT 4 ID, 'D' StringID, 'and again' StringText
UNION SELECT 5 ID, 'E' StringID, 'yet again' StringText) data
WHERE ID IN (@integer)";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
List<int> integers = new List<int>{ 1, 2, 3 };
List<string> strings = new List<string> { "A", "B", "C" };
var parameters = new {str = strings, integer = integers };
//fails here
IEnumerable<string> intTest = conn.Query<string>(sqlIntegerIn, parameters, commandType: System.Data.CommandType.Text);
//and here
IEnumerable<string> stringTest = conn.Query<string>(sqlStringIn, parameters, commandType: System.Data.CommandType.Text);
}
发布于 2017-11-29 19:45:37
如果你对处理空列表感兴趣,我想补充一个重要的注意事项,也就是让IN
子句成为optional
。为此,我添加了一个属性来包含计数,比如public int InClauseCount => InClauseList?.Length ?? 0;
然后在sql中使用计数,如下所示...
Select field1, field2
from Table1
where (some condition)
AND (@InClauseCount = 0 OR field1 IN @InClauseList)
我希望这能帮助到外面的人。我花了太长时间试图解决这个问题,部分原因是我是Dapper的新手。
https://stackoverflow.com/questions/19932776
复制相似问题