如何使用 Dapper 插入多条记录,同时还包括其他动态参数?

How do I insert multiple records using Dapper while also including other dynamic parameters?

这是我正在尝试做的截断示例:

var stuffTOSave = new List<SomeObject> {
    public int OtherTableId { get; set; }
    public List<Guid> ComponentIds { get; set; }
};

var sql = @"CREATE TABLE Components( ComponentId uniqueidentifier PRIMARY KEY )
INSERT INTO Components VALUES (@WhatGoesHere?)

SELECT * FROM OtherTable ot
JOIN Components c on c.ComponentId = ot.ComponentId
WHERE Id = @OtherTableId

DROP TABLE Components"

Connection.Execute(sql, stuffToSave);

我从 other SO questions 了解到,您可以使用 Dapper 将列表传递到插入语句中,但我找不到任何传递列表和另一个参数的示例(在我的示例中,OtherTableId),或者有一个非对象列表(List<Guid> 而不是 List<SomeObject>,它具有要引用的名称的属性)。

对于第二期,我可以 select 将 ComponentId 放入列表中,给它们起一个像这样的名字:

stuffToSave.ComponentIds.Select(c => new { ComponentId = c })

但是我不确定要在我的 sql 查询中放入什么,以便 dapper 理解从我的 ComponentIds 列表中获取 ComponentId 属性(第 7 行)

我仍然想知道完成此操作的真正方法,但我有使用字符串插值的解决方法:

var sql = $@"CREATE TABLE Components( ComponentId uniqueidentifier PRIMARY KEY )
    INSERT INTO Components VALUES ('{string.Join($"'),{Environment.NewLine}('", request.ComponentIds)}')

    SELECT * FROM OtherTable ot
    JOIN Components c on c.ComponentId = ot.ComponentId
    WHERE Id = @OtherTableId

    DROP TABLE Components"

我不担心 SQL 注入,因为这只是插入一个 Guid 列表,但我宁愿尽可能避免使用这种方法。