bulkcopy with primary key not working

c# datatable sql sqlbulkcopy


There are columns in my database table and a primary key.

In my C# program, I want to bulkcopy data from a datatable.

I received an exception when my table had a primary key since it had six columns as opposed to my datatable's five.

Please advise what I should do.

Should my datatable in C# have a primary key added?

(Please let me know if you need any codes.)

The table of data is this.

private DataTable getBasicDataTable()
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("customerID", typeof(int));
            dataTable.Columns.Add("firstName", typeof(string));
            dataTable.Columns.Add("lastName", typeof(string));
            dataTable.Columns.Add("showsNumber", typeof(int));
            dataTable.Columns.Add("visitNumber", typeof(int));
            dataTable.Columns.Add("cancellation", typeof(int));
            return dataTable;

although I have more fields in my database table with the exact same number of rows.ID first key,


My database's primary key is deleted, and everything functions as intended.

11/21/2014 12:02:49 PM

Accepted Answer

I figured it out on my own.

bc.ColumnMappings.Add("customerID", "customerID");
                sbc.ColumnMappings.Add("firstName", "firstName");
                sbc.ColumnMappings.Add("lastName", "lastName");
                sbc.ColumnMappings.Add("showsNumber", "showsNumber");
                sbc.ColumnMappings.Add("visitNumber", "visitNumber");
                sbc.ColumnMappings.Add("cancellation", "cancellation");
11/21/2014 12:17:22 PM

Popular Answer

Utilize SqlBulkCopy.ColumnMappings

Column mappings define the relationships between columns in the data source and columns in the destination.


If the data source and the destination table have the same number of columns, and the ordinal position of each source column within the data source matches the ordinal position of the corresponding destination column, the ColumnMappings collection is unnecessary. However, if the column counts differ, or the ordinal positions are not consistent, you must use ColumnMappings to make sure that data is copied into the correct columns.

To utilize it, refer to the example at SqlBulkCopyColumnMapping.

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