1. /// <summary>
  2. /// 用TemporaryTable + SqlBulkCopy + Dapper的方法实现批量插入
  3. /// </summary>
  4. /// <param name="list"></param>
  5. /// <returns></returns>
  6. int InsertMany<T>(List<T> list, string tableName, string columnsStr, string connectionString)
  7. {
  8. if (string.IsNullOrWhiteSpace(tableName)
  9. || string.IsNullOrWhiteSpace(columnsStr)) { return 0; }
  10. var asTable = JsonConvert.DeserializeObject<DataTable>(JsonConvert.SerializeObject(list));
  11. asTable.AcceptChanges();
  12. using (var connection = new SqlConnection(connectionString))
  13. {
  14. connection.Open();
  15. var trans = connection.BeginTransaction();
  16. var tempTableName = "#TempInsertMany";
  17. //生成临时表
  18. connection.Execute($@"SELECT TOP (0) {columnsStr} INTO [{tempTableName}] FROM {tableName}"
  19. , null, trans);
  20. //把数据移到临时表
  21. using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, trans))
  22. {
  23. bulkCopy.BulkCopyTimeout = (int)TimeSpan.FromSeconds(30).TotalSeconds;
  24. bulkCopy.BatchSize = 100;
  25. bulkCopy.DestinationTableName = tempTableName;
  26. bulkCopy.WriteToServer(asTable.CreateDataReader());
  27. }
  28. //把临时表的数据添加到表中
  29. var rst = connection.Execute(
  30. $@"INSERT INTO {tableName} ({columnsStr})
  31. select {columnsStr} from {tempTableName}", transaction: trans);
  32. trans.Commit();
  33. return rst;
  34. }
  35. }

参考

Bulk Insert with Dapper