一段时间以来,我一直在尝试使用 IEnumerable<string>
,但没有成功。用WHERE IN
Dapper 中的子句。
在文档中,确实说 IEnumerable<int>
支持在 WHERE IN
中使用但我什至无法让它工作。
Dapper allow you to pass in IEnumerable<int> 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);
}
最佳答案
要执行这里需要的操作,dapper 需要动态更改 SQL - 因此它需要真正确保它在做正确的事情。常规有效的 SQL 语法包括括号:
WHERE StringId IN (@str)
为了消除歧义,voodoo dapper 语法省略括号:
WHERE StringId IN @str
如果它检测到这一点,它会查找名为 str
的参数,并将其扩展为以下之一:
WHERE 1=0 -- if no values
WHERE StringId = @str -- if exactly one value
WHERE StringId IN (@str0, @str1, ...) -- if more than one value
但是简短的版本:删除括号。
关于c# - 如何在 Dapper 中使用 'Where In',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19932776/