我需要使用Dapper将成千上万个ID的列表作为参数传递给查询。
即使没有a limit WRT the amount of parameters,您也可以将其发送到SQL Server,遍历集合并创建大量参数是不明智的解决方案。
幸运的是,我已经看到您可以发送一个XML字符串,查询可以解压缩using XTbl.value and .nodes()。
但是我不知道如何通过Dapper传递此XML字符串。
答案 0 :(得分:0)
最后并不难,只是花了点功夫将各种知识点和一些反复试验结合在一起。
这是查询的简化版本:
SELECT DISTINCT [regular_Person].[Idf] AS [Idf]
, [regular_Person].[FirstName]
, [regular_Person].[LastName]
FROM [regular].[Person] [regular_Person]
WHERE [regular_Person].[Idf] IN (
SELECT Idf
FROM (
SELECT Idf = XTbl.value('.', 'NVARCHAR(10)')
FROM @Idfs.nodes('/root/Idf') AS XD(XTbl)
) AS XmlToData
)
ORDER BY
[regular_Person].[LastName]
, [regular_Person].[FirstName]
它以.sql文件的形式嵌入到我的解决方案中,我使用QueryRetriever
类进行读取-检查https://codereview.stackexchange.com/q/214250/10582的代码。
传递给查询的ID需要转换为XML字符串:
var idfsAsXml = new XDocument(
new XElement("root",
excelRecords
.Select(x => x.Idf)
.Distinct()
.Select(x => new XElement("Idf", x))))
.ToString();
然后我使用Dapper的DynamicParameters
创建一个参数:
var dynamicParameters = new DynamicParameters();
dynamicParameters.Add("@Idfs", idfsAsXml, DbType.Xml, ParameterDirection.Input);
然后我将该参数传递为DbType.Xml
(与ParameterDirection.Input
一起使用):
using (var connection = new SqlConnection(_connectionString))
{
regularRecords = connection.Query<RegularRecord>(
QueryRetriever.GetQuery("GetRegularRecords.sql"),
dynamicParameters
)
.ToList();
}
也许这对其他人有帮助。