SqlBulkCopy with Byte[] DataTable column error

bytearray c# sqlbulkcopy strongly-typed-dataset

Question

I have a strongly typed dataset containing a datatable with one of the columns as a byte[] column that I'm trying to insert into a binary(4) database table field. I'm able to set the byte[] column values without any problems, but I receive the following exception when I run sqlbulkcopy on the datatable:

"The given value of type Int32 from the data source cannot be converted to type binary of the specified target column."

The datatable is a large datatable and the sqlbulkcopy works fine with the datatable and database table minus the byte[]/binary(4) columns. The following is the code that I've inserted that is breaking SqlBulkCopy using .NET 2.0.

byte[] codeByteArray = GetByteArray();
dt.byteArrayCol = codeByteArray;

...

using(SqlBulkCopy bc = new SqlBulkCopy(conn))
{
    bc.DestinationTableName = dt.TableName;
    bc.WriteToServer(dt);
    bc.Close();
}

Accepted Answer

I discovered my problem. The Byte[] column in my datatable was not in the same ordinal position as the corresponding database column ordinal. The datatable column ordinal was 56 while the database column ordinal was 8, thus either the datatable needed to be re-organized or the columnmapping for the sqlbulkcopy. Reorganizing the datatable was much easier and quicker.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why