Mapping columns in a DataTable to a SQL table with SqlBulkCopy

c# datatable sql sqlbulkcopy

Question

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);
}
1
24
7/11/2018 11:15:17 PM

Accepted Answer

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

42
5/23/2017 12:10:08 PM

Popular Answer

This became such a common task that I wrote this helper for it:

public static void AutoMapColumns(SqlBulkCopy sbc, DataTable dt)
{
    foreach (DataColumn column in dt.Columns)
    {
        sbc.ColumnMappings.Add(column.ColumnName, column.ColumnName);
    }
}

Since I was creating the DataTable myself, I named its columns the same as the SQL table.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow