Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Bulk Copy "The given value of type String from the data source cannot be converted to type datetime of the specified target column" using ASP.NET

I'm working on an ASP.NET MVC4 projet and I'm trying to export data from an xlsx file (Excel 2010 file) to my database by using SQL Bulk Copy. My Excel file contains only 2 columns : the first contains numbers (from 1 to 25) and the second contains characters (successive series of "a, b, c")

This is how I try to do in order to export data but I got the error "The given value of type String from the data source cannot be converted to type int of the specified target column" :

public ActionResult Bulk()
{    
    string xConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\maarab\Documents\BulkCopy.xlsx;Extended Properties=Excel 12.0;";
    using (OleDbConnection connection = new OleDbConnection(xConnStr))
    {
        OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
        connection.Open();    
        string dbConnection = ((EntityConnection)db.Connection).StoreConnection.ConnectionString;

        // Create DbDataReader to Data Worksheet
        using (DbDataReader dr = command.ExecuteReader())
        {
            using (var bulkCopy = new SqlBulkCopy(dbConnection))
            {    
                bulkCopy.DestinationTableName = "bm_test" 
                bulkCopy.WriteToServer(dr); //here I got the error    
            }
        }

        return RedirectToAction("Index");
}

Any idea about what's causing this error?

like image 546
Traffy Avatar asked Jul 19 '13 08:07

Traffy


3 Answers

SqlBulkCopy.WriteToServer(DataTable) fails with confusing messages if the column order of the DataTable differs from the column order of the table definition in your database (when this causes a type or length incompatibility). Apparently the WriteToServer method does not map column names.

like image 198
subsci Avatar answered Sep 23 '22 15:09

subsci


Mine was whining about this until I set the orders manually like so:

SqlBulkCopy sbc = new SqlBulkCopy(ConnectionString, SqlBulkCopyOptions.UseInternalTransaction);
sbc.DestinationTableName = "agSoilShapes";
sbc.ColumnMappings.Add("Mukey", "Mukey");
sbc.ColumnMappings.Add("Musym", "Musym");
sbc.ColumnMappings.Add("Shapes", "Shapes");

DataTable dt = new DataTable();
dt.Columns.Add("Mukey", typeof(SqlInt32));
dt.Columns.Add("Musym", typeof(SqlString));
dt.Columns.Add("Shapes", typeof(SqlGeometry));

Thanks to others (@subsci) for comments leading me in this direction :)

like image 21
jocull Avatar answered Sep 26 '22 15:09

jocull


I have received a similar error when using EntityFramework.BulkInsert package. In this case the underlying cause was an order mismatch between database table columns and generated model metadata columns (database-first).

like image 40
Alexei - check Codidact Avatar answered Sep 25 '22 15:09

Alexei - check Codidact