【发布时间】:2013-11-24 19:32:45
【问题描述】:
一段时间以来,我一直在尝试在 Dapper 中使用 IEnumerable<string> 和 WHERE IN 子句,但没有成功。
在文档中,确实说 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);
}
【问题讨论】:
-
你为什么不使用 Linq ? Dapper 有一个助手库可以为您完成这项工作:sqlinq.codeplex.com/releases/view/88056
-
@Aybe 没必要; dapper 明确处理这种情况