Inserting DBNull value to a DataTable column before bulk copy

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

Answers


Use the null coalescing operator.

row["PeakType"] = peakType ?? DBNull.Value;

If peakType is null, it will use the correct DB null value.


Need Your Help

asp.net mvc 4 end request in AuthorizeAttribute

c# asp.net-mvc asp.net-web-api

In our asp.net mvc 4 project, we use AuthorizeAttribute to implement access control,our code like this

Android App Stops Working Immediately

java android

I have created an android app that features an add button, a subtract button, and a counter variable.