c# - 为什么 Dapper 无法返回多个插入的行 ID?

标签 c# .net sql-server dapper

我有一个 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/

相关文章:

.net - OData Web API 操作参数反序列化

.net - 真空分析运行非常缓慢,导致其他系统超时

sql - 通过选择查询在表中插入行

c# - 样板代码替换——这段代码有什么不好的地方吗?

c# - 方法隐藏加上重写调用决策

c# - asp 下拉菜单,列表项随我的 div 滚动

c# - Controller 以字典为参数的 action stripping to dot

sql-server - 计算柱性能

c# - 检查 dbgeometry dbgeometry/dbgeography 点是否在多边形内

c# - 如何访问放置在该 void 之外的 async void 中的字符串的值