如何使用 Dapper.Contrib 取回新插入记录的密钥?

How do I get back the key for a newly inserted record using Dapper.Contrib?

我有这样的代码:

db.Insert(myObject);

myObject 类型的键是 RDBMS 自动生成的 System.Guid 类型。

然后我想插入将使用该键与其父对象关联的子对象。

foreach(var child in myObject.ChildObjects) {
   child.ParentId = parentIdThatISomehowSaved; //this is what I don't know how to do
   db.Insert(child);
}

我正在插入时通过 SQL 服务器为记录分配一个新的 Guid

获取新记录 ID 的最佳方法是什么,以便我可以将其作为外键填充到子对象上? Dapper.Contrib.Extensions.Insert 方法 returns 一个 long,那么有没有办法使它与 Guid 一起工作?

更新:2022 年 5 月 2 日

source code 看来,此功能现已实现。 不过我还没有测试过。
Insert<T> 方法似乎将 return(它不会映射到实体 属性)新生成的数字 ID(return 类型如果仅插入单个实体,则方法为 long)。如果正在插入实体列表,它将插入 return 行数。

我不确定如何使用 GUID ID

代码注释如下:

/// Inserts an entity into table "Ts" and returns identity id or number of inserted rows if inserting a list.  
...  
...  
/// <returns>Identity of inserted entity, or number of inserted rows if inserting a list</returns>

此外,观察插入单个实体的 code 并且应该 return 根据上面的代码注释新生成的 ID:

if (!isList)    //single entity
{
    returnVal = adapter.Insert(connection, transaction, commandTimeout, name, sbColumnList.ToString(),
    sbParameterList.ToString(), keyProperties, entityToInsert);
}
else
{
    //insert list of entities
    var cmd = $"insert into {name} ({sbColumnList}) values ({sbParameterList})";
    returnVal = connection.Execute(cmd, entityToInsert, transaction, commandTimeout);
}

原答案:

Insert method of Dapper Contrib does not return the newly generated ID. This is because Contrib is built over Dapper which neither map the newly generated ID to the entity by default nor does it returns it. But there are ways to return the newly generated ID using Dapper. Those are discussed , here and .

Dapper Extensions(Dapper 的其他查询生成器)默认支持此功能。详情请参考this回答

一种方法是绕过Contrib并使用Dapper;使用链接中解释的任何方式获取新生成的 ID(OUTPUT 参数或 @@IDENTITY 等)。

使用 Contrib 执行此操作的其他方法是通过在调用 Dapper(如链接中所述;@@IDENTITYInsert.

第三种方法是显式分配 ID,而不是自动生成 ID。您可以使用 [ExplicitKey] 属性来实现此目的。您还需要相应地更改数据库。

[Key] should be used for database-generated keys (e.g. autoincrement columns), while [ExplicitKey] should be used for explicit keys generated in code.

更激进的解决方案是修改 Contrib 代码,使 Insert return 新生成 ID。

顺便说一句,我发现一个issue类似于你的问题;看看对你有没有帮助。