I have a data table that I use for Bulk Copying into a SQL server Database: I define its columns as follows:
dt.Columns.Add("BaseID", typeof(Int32));
dt.Columns.Add("ContractID", typeof(DateTime));
dt.Columns.Add("TermID",typeof(Int32));
dt.Columns.Add("Price",typeof(Decimal));
dt.Columns.Add("PeakType",typeof(String));
Now the PeakType column could actually be a string or it could be null. So when I add rows to my data table I do this.
DataRow row = dt.NewRow();
row["BaseID"] = baseID;
row["ContractDate"] = contractDate;
row["TermID"] = termID;
row["Price"] = price;
row["PeakType"] = peakType; //How would I assign If I want to assign DBNull?
How do I specify DBNull.Value if peakType is null so that my bulk copy would correctly insert a null in the column in the SQL server table
The two possible reasons I know of for the does not allow DBNull error are: Columns are in the wrong order, which is solved by either putting them in the same order as their Database Ordinal, or by performing a Column Mapping. KeepNulls is enabled, and DBNull. Value (or null ?) are set in the DataTable.
DBNull represents a nonexistent value returned from the database. In a database, for example, a column in a row of a table might not contain any data whatsoever. That is, the column is considered to not exist at all instead of merely not having a value. A DBNull object represents the nonexistent column.
DBNull is a singleton class, which means only this instance of this class can exist. If a database field has missing data, you can use the DBNull. Value property to explicitly assign a DBNull object value to the field. However, most data providers do this automatically.
Use the null coalescing operator
.
row["PeakType"] = peakType ?? DBNull.Value;
If peakType
is null, it will use the correct DB null value.
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