简体   繁体   中英

SqlBulkCopy dbnull.value error

I am trying to insert rows from an excel file into sql server 2000 using bulkcopy. In the table there is a 'rowguid' field and its default value is set to (newid()) and cannot except null values. Also RowGUID is set to "Yes".

In my code i remove the column mapping for rowguid . Here is my code.

if (dr.HasRows)
{
    using (SqlBulkCopy bulkCopy =
        new SqlBulkCopy(sqlConnectionString))
        {
           bulkCopy.DestinationTableName = "configtest";
           SqlBulkCopyColumnMapping value = new SqlBulkCopyColumnMapping("rowguid", "rowguid");
           bulkCopy.ColumnMappings.Remove(value);
           bulkCopy.WriteToServer(dr);
         }


 }

I get column 'rowguid does not allow dbnull.value

definition for that field is : rowguid , uniqueidentifier, allow nulls unticked.

Instead of

bulkCopy.ColumnMappings.Remove(value);

Try

bulkCopy.ColumnMappings.Add(value);

You have to remove the mapping that is referenced. So if you already have ColumnMappings you have to do it like this:

var mapping = bulkCopy.ColumnMappings.Cast<SqlBulkCopyColumnMapping>()
            .Single(x => x.DestinationColumn == "rowguid"));

bulkCopy.ColumnMappings.Remove(mapping);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM