Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The given value of type String from the data source cannot be converted to type bigint of the specified target column

Tags:

c#

sql

That's my code :

protected void SendToServer_Click(object sender, EventArgs e)
{
    DataTable Values = Session["valuesdt"] as DataTable;

    if (Values.Rows.Count > 0)
    {
        //Fix up default values
        for (int i = 0; i < Values.Rows.Count; i++)
        {
            Values.Rows[i]["Mobile1"] = Values.Rows[i]["Mobile1"].ToString() == "" ? 0 : double.Parse(Values.Rows[i]["Mobile1"].ToString());
            Values.Rows[i]["Mobile2"] = Values.Rows[i]["Mobile2"].ToString() == "" ? 0 : double.Parse(Values.Rows[i]["Mobile2"].ToString());
            Values.Rows[i]["Tel"] = Values.Rows[i]["Tel"].ToString() == "" ? 0 : double.Parse(Values.Rows[i]["Tel"].ToString());
            Values.Rows[i]["Category"] = Values.Rows[i]["Category"].ToString();
        }

        DataTable dv = Values.DefaultView.ToTable(true, "Mobile1", "Mobile2", "Tel", "Category");
        BulckCopyDataTable(dv, "client", 1000);
    }
}

public void BulckCopyDataTable(DataTable dt,string DestinationTable,int batchSize)
{
    connection.Open();

    using (SqlBulkCopy copy = new SqlBulkCopy(connection))
    {
        copy.BatchSize = batchSize;
        copy.DestinationTableName = DestinationTable;
        copy.WriteToServer(dt);
        connection.Close();
    }
}

I have no idea why this error is been throws in the database :

Mobile1 bigint, Mobile2 bigint, Tel bigint, Category nvarchar(MAX)
like image 844
Sora Avatar asked Mar 24 '23 17:03

Sora


1 Answers

I found an answer in this bytes.com thread.

All you have to do is map the columns of the source to the destination table with the use of SqlBulkCopyColumnMapping.

bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(0, 1));
bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(1, 2));
bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(2, 3));
bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(3, 6)); //look here, index is different
bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(4, 8)); //and again
bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(5, 9));

I also found the same solution here before finding the above, but in my case I had some fields missing in the source. The fields were in the correct order although it referred to the actual INDEX/ORDER of the fields. If I didn't have the missing fields it would have worked.

like image 55
Sabo Avatar answered Mar 26 '23 05:03

Sabo