使用 Dapper INSERT 在 SQL Azure 中花费的时间太长

INSERT with Dapper takes too long in SQL Azure

我有一个实体实例,具有一对多关系(项目)。我正在尝试通过 Dapper 将其插入到 SQL Azure 实例中。

项目数约为 3.5k

using (var transaction = connection.BeginTransaction())
{
  // (...) x inserted here, we want to insert the items next...
  connection.Execute(TSQL_InsertStatement, x.Items, transaction);
  transaction.Commit();
}

我相信此操作会生成大量单独的 INSERT,这可能是个问题。我已经尝试将其重构为 "manually-generated-sql" 解决方案,该解决方案生成了 4x 插入(1k、1k、1k、500 行),但是执行此操作在本地占用了 2[s]。

在同一事务中使用多个插入在 Azure SQL 数据库中通常不是一个好主意。

您应该使用批处理来提高插入查询的性能,请参阅 https://azure.microsoft.com/en-us/documentation/articles/sql-database-use-batching-to-improve-performance/。 如果可能的话,我会推荐 table 值参数、批量插入或多个参数化插入。参考文章中描述了这些场景。

Azure Sql 数据库也有 JSON 支持,因此如果您的原始来源是 JSON 对象数组,您可以将整个 JSON 作为文本推送并在 SQL 端使用 OPENJSON(仍然没有证据表明这比其他方法更快)。