Creating a DataTable Bulk Copy Example - madcodemonkey/ClassToDataTable GitHub Wiki

To see all the surrounding code, see the Bulk Copy Example in the example code.

/// <summary>This examples shows how to use the ClassToDataTable service and SQLBulkCopy together.</summary>
private static async Task SqlCopyWithoutHelperAsync(SqlConnection sqlConnection, string tableSchema, 
	string tableName, int batchSize, int bulkCopyTimeoutInSeconds, List<Person> people)
{
   var classToDataTableService = new ClassToDataTableService<Person>();

   var myBulkCopy = new SqlBulkCopy(sqlConnection)
   {
      DestinationTableName = $"{tableSchema}.{tableName}", 
      BatchSize = batchSize, 
      BulkCopyTimeout = bulkCopyTimeoutInSeconds
   };

   // Column mappings for SQLBulkCopy
   foreach (DataColumn column in classToDataTableService.Table.Columns)
   {
      myBulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
   }

   foreach (var item in people)
   {
      classToDataTableService.AddRow(item);

      if (classToDataTableService.Count % myBulkCopy.BatchSize == 0)
      {
         // WRITE to SERVER!
         await myBulkCopy.WriteToServerAsync(classToDataTableService.Table);
         classToDataTableService.Clear();
      }
   }

   // Flush any remaining items.
   if (classToDataTableService.Count > 0)
   {
      // WRITE to SERVER!
      await myBulkCopy.WriteToServerAsync(classToDataTableService.Table);
   }
}
⚠️ **GitHub.com Fallback** ⚠️