I'm trying to use SqlBulkCopy to import a bunch of data to our website. In most of the other areas we're using Entity model which uses byte arrays to represent binary data in SQL. However, SqlBulkCopy seems to be confusing byte[] with string. Everything seems to be working fine except for this one binary column which throws an exception: "The given value of type String from the data source cannot be converted to type binary of the specified target column."
I've created a small test case to illustrate the problem:
using System.Data;
using System.Data.SqlClient;
namespace SqlBulkCopyTest
{
class Program
{
static void Main(string[] args)
{
DataTable table = new DataTable("BinaryData");
table.Columns.Add("Data");
for (int i = 0; i < 10; i++)
{
var row = table.NewRow();
row["Data"] = new byte[5] { 1, 2, 3, 4, 5 };
table.Rows.Add(row);
}
using (var connection =
new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=TestBulkCopy;Integrated Security=True"))
{
connection.Open();
using (var copier = new SqlBulkCopy(connection))
{
copier.DestinationTableName = table.TableName;
/* EXCEPTION HERE: */ copier.WriteToServer(table);
}
}
}
}
}
This uses a test database with a BinaryData
table which has a single binary(5)
column named Data
.
Any help would be greatly appreciated
WriteToServer(DataTable)Copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.
The SqlBulkCopy class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance.
By default, a bulk copy operation is its own transaction. When you want to perform a dedicated bulk copy operation, create a new instance of SqlBulkCopy with a connection string, or use an existing SqlConnection object without an active transaction.
Instead of:
table.Columns.Add("Data");
Add the "Data" column as a binary:
table.Columns.Add("Data", typeof(Byte[]));
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