I would like to know how I can map columns in a database table to the datatable in c# before adding the data to the database.
using (SqlBulkCopy s = new SqlBulkCopy(conn)) { s.DestinationTableName = destination; s.WriteToServer(Ads_api_ReportData); }
The SqlBulkCopy class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but SqlBulkCopy offers a significant performance advantage over them.
Bulk means many things. So with the use of SqlBulkCopy you can send a large amount of data from any source to SQL Server database. For example you have a collection of data in XML format and you want to save this data into your database table. You can do this very easily.
Upload the data to the temporary table, then perform the SqlBulkCopy update. Using SqlBulkCopy(), upload the datatable's data to the temporary table. Then execute a SQL command to update the main table's data from the temporary table. Finally drop the temporary table.
You probably need some thing like
public void BatchBulkCopy(DataTable dataTable, string DestinationTbl, int batchSize) { // Get the DataTable DataTable dtInsertRows = dataTable; using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity)) { sbc.DestinationTableName = DestinationTbl; // Number of records to be processed in one go sbc.BatchSize = batchSize; // Add your column mappings here sbc.ColumnMappings.Add("field1","field3"); sbc.ColumnMappings.Add("foo","bar"); // Finally write to server sbc.WriteToServer(dtInsertRows); } }
Ref: How to use SqlBulkCopyColumnMappingCollection? . .
Seel also http://www.codeproject.com/Articles/18418/Transferring-Data-Using-SqlBulkCopy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With