How To Use BulkCopy To Insert A DataTable In C#



TODO:

Have you ever wanted to insert the contents of a DataTable efficiently using SqlClient.BulkCopy?

 

SOLUTION:

public static void FillMonteCarloSimulationResults(DataTable InDataTable)
{
     using (SqlBulkCopy bulkCopy = new SqlBulkCopy("myconnectionstring")
     {
          //***NOW Do column mappings.  This maps columns from DataTable (left) to DB Table (right)
          bulkCopy.DestinationTableName = "Results";
          bulkCopy.ColumnMappings.Add("EmployeeId", "EmployeeId");
          bulkCopy.ColumnMappings.Add("Name", "Name");
          bulkCopy.WriteToServer(InDataTable);            
     }
}

 

NOTES:

This example will take the DataTable, map the columns, then preform BulkCopy



Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading