我有一个 SQL Server 表,使用以下方法将行插入到该表中:
var sql = @"
DECLARE @InsertedRows AS TABLE (Id BIGINT);
INSERT INTO Person ([Name], [Age]) OUTPUT Inserted.Id INTO @InsertedRows
VALUES (@Name, @Age);
SELECT Id FROM @InsertedRows;";
Person person = ...;
var id = connection.Query<long>(sql, person).First();
这一切都很好,但是如果我尝试插入多个项目并使用以下方法返回所有插入的 ID:
IEnumerable<Person> people = ...;
var ids = connection.Query<long>(sql, people);
我得到一个错误:
System.InvalidOperationException : An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context
at Dapper.SqlMapper.GetCacheInfo(Identity identity, Object exampleParameters, Boolean addToCache)
at Dapper.SqlMapper.d__23`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
如何在 Dapper 中返回多个插入的 ID?
最佳答案
某处某处需要循环。您有一个插入一行的 sql 语句,并在列表中发送代码。由于您喜欢字符串文字中的 SQL,因此我会坚持一次插入一个人,将循环放在 C# 中并使用 SELECT SCOPE_IDENTITY()
在 C# 中恢复每个 id。您不再需要 @InsertedRows 或 OUTPUT。
如果您真的想在 SQL 中循环,我相信您需要查看表值参数以传递您的插入列表。 Dapper 很乐意返回多个 Id。它提示多个人作为输入参数。
总有一天,希望很快,我们将回顾字符串文字中的 SQL,就像我们目前看 goat sacrifice 一样。 .
关于c# - 为什么 Dapper 无法返回多个插入的行 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39884768/