简体   繁体   中英

SqlBulkCopy giving InvalidOperationException Error that I am inserting Null Values, but all values are non-null in the table

I have a table where one of the fields is "InDatabase" (SQL Server "bit" type) which does not allow nulls.

I create a table and add a few hundred rows to it, where InDatabase is always assigned a value (InDatabase refers to whether the row is in another database)

When I call SqlBulkCopy, it is giving me an InvalidOperationException Error, with the message of:

"Column 'InDatabase' does not allow DBNull.Value."

Each Row Is Created as such:

ProductionDatabaseDataSet.EntriesV2Row NewRow = this.InsertTable.NewEntriesV2Row();

NewRow.MeetEntryID = MeetEntryID;
NewRow.EventID = EventID;
NewRow.MeetID = MeetID;
NewRow.AthleteID = AthleteID;
NewRow.Exhibition = Exhibition;
NewRow.Bonus = Bonus;
NewRow.EnterEvent = true;
NewRow.InDatabase = true;
if (AutoTime != null)
    NewRow.AutoTime = AutoTime ?? -1;
if (CustomTime != null)
    NewRow.CustomTime = CustomTime ?? -1;

this.InsertTable.AddEntriesV2Row(NewRow);

Then, after the above is called around 300 times, the SqlBulkCopy is called:

SqlBulkCopy bulkCopy = new SqlBulkCopy(this.Connection.ConnectionString);
bulkCopy.DestinationTableName = this.Adapter.TableMappings[0].DataSetTable;
            bulkCopy.BatchSize = BatchSize;
bulkCopy.WriteToServer(InsertTable); //Throwing the error

I use this exact same format on about a dozen other tables with no problem.

OK, I got it to work, but not really figured it out. I changed the bulkCopy section to this:

bulkCopy.DestinationTableName = this.Adapter.TableMappings[0].DataSetTable;
for (int i = 0; i < this.Adapter.TableMappings[0].ColumnMappings.Count; i++)
    bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(
                this.Adapter.TableMappings[0].ColumnMappings[i].SourceColumn.ToString(),
                this.Adapter.TableMappings[0].ColumnMappings[i].DataSetColumn.ToString()));
bulkCopy.BatchSize = BatchSize;


bulkCopy.WriteToServer(InsertTable);

Not real sure why the dozen other times I did this without setting the table mappings like this worked, but for some reason, with this table, it will not work unless I do the above.

If I understood your problem correctly...

I think the problem is defining NULL value in c# .net and SQL . The mean of NULL of your programming language will not be the same in SQL. In SQL the NULL value represnt by System.DBNull Class

Just check How to Handle Null and DBNull

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