【问题标题】:How do I insert multiple records using Dapper while also including other dynamic parameters?如何使用 Dapper 插入多条记录,同时还包括其他动态参数?
【发布时间】:2020-01-24 15:57:31
【问题描述】:

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

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&lt;Guid&gt;List&lt;SomeObject&gt; 具有要引用的名称的属性相对)。

对于第二个问题,我可以将ComponentIds 选择到一个列表中,并为其命名:

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

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

【问题讨论】:

    标签: c# sql dapper


    【解决方案1】:

    我仍然想知道实现这一点的真正方法,但我有这个使用字符串插值的解决方法:

    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 列表,但如果可能的话,我宁愿避免这种方法。

    【讨论】:

      猜你喜欢
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 2016-01-04
      • 2012-04-18
      • 2020-10-06
      • 2015-05-10
      相关资源
      最近更新 更多