1
votes

I have a MS SQL Local DB which allows a column fields to have null values. However, when I tried to set (DateTime?) null to the field, there was an exception "System.ArgumentException Cannot set Column 'DeliveryTime' to be null. Please use DBNull instead.". So i tried replacing (DateTime?) null to DBNull.value. Then a compile error popped up

"CS0173 C# Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'System.DBNull'"

I'm using MS VS 2017 community. What shall I do about this?

DataRow row; 
string rs; 
DateTime dt; 

row["DeliveryTime"] = DateTime.TryParse(rs, out dt) ? dt : (DateTime?) null;
// I replaced (DateTime?) null to DBNull.Value and got a compile error
1
Please show us the code where you are setting these values. - Ron Beyer
Please post your code and more details. - Jonathan Alfaro
DataRow row; string rs; DateTime dt; row["DeliveryTime"] = DateTime.TryParse(rs, out dt) ? dt : (DateTime?) null; // I replaced (DateTime?) null to DBNull.Value and got a compile error - Andy Darabont

1 Answers

2
votes

It sounds like you are doing (in either an assignment or a call - some kind of expression, basically):

val == null ? DBNull.Value : val.Value

or something similar; the problem is that the two outcomes of a conditional operator need to have a type in common. The easiest fix here would be

((object)val) ?? DBNull.Value

This uses null-coalescing instead, along with the fact that a Nullable<T> that doesn't have a value will convert to a null reference.