37

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);
}
Nat
  • 325
  • 4
  • 14
user2545743
  • 799
  • 2
  • 8
  • 10
  • 1
    SQL bulk copy works without the column mappings also,however there is a catch that the order in which datatable rows are initialized - sql server expects the same column order in the table. Hence adding the columnmappings is must while using sqlbulkcopy @user2545743 – dhinesh Dec 31 '19 at 14:17

6 Answers6

50

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

Community
  • 1
  • 1
StackTrace
  • 9,190
  • 36
  • 114
  • 202
40

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.

L. Norman
  • 483
  • 7
  • 21
Evan M
  • 2,573
  • 1
  • 31
  • 36
14

It might be useful to know that if the columns in the source query (or table) and the target table have the same name and are in the exact same order, then there is no need to write out the mappings explicitly, because SqlBulkCopy will create a default mapping with this default order.

Hugo Nava Kopp
  • 2,906
  • 2
  • 23
  • 41
2

Use the ColumnMappings:

s.ColumnMappings.Add("Name", "Name");
s.ColumnMappings.Add("Address", "Address");
Ben Gulapa
  • 1,619
  • 14
  • 10
1

The method Add on ColumnMappings collection allows you to map your columns from source table to destination table. The method ColumnMappings.Add accepts four different ways to map your columns.

SQLBulkCopy is very much strict on data type of both the columns which you have to consider while adding it to ColumnMappings collection

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Laxmikant
  • 588
  • 4
  • 11
0

You can use below code

                using (OleDbConnection con = new OleDbConnection(excelCS))
                {
                    OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", con);
                    con.Open();
                    // Create DbDataReader to Data Worksheet  
                    DbDataReader dr = cmd.ExecuteReader();
                    // SQL Server Connection String  
                    //string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                    string CS = objCommon.TestConnection;
                    // Bulk Copy to SQL Server   
                    SqlBulkCopy bulkInsert = new SqlBulkCopy(CS);

                    bulkInsert.ColumnMappings.Add("Kcode", "Kcode");
                    bulkInsert.ColumnMappings.Add("MDMCode", "MDMCode");

                    bulkInsert.DestinationTableName = "tbl_MDMKcodeMapping";
                    bulkInsert.WriteToServer(dr);
                    
                    lblMessage.Text = "Your file uploaded successfully";
                    lblMessage.ForeColor = System.Drawing.Color.Green;
                }

Please note that in

  bulkInsert.ColumnMappings.Add("Kcode", "Kcode");

The first parameter should be your Excel column name and the second parameter should be your SQL table column name

Mohsin Khan
  • 175
  • 11