Do I have a DateTime? which I am trying to insert into a field using DbParameter . I create a parameter like this:
DbParameter datePrm = updateStmt.CreateParameter(); datePrm.ParameterName = "@change_date";
And then I want to put a DateTime? value DateTime? in dataPrm.Value , given null s.
At first I thought I would be smart:
datePrm.Value = nullableDate ?? DBNull.Value;
but error with error
The operator '??' can't apply to operands like "System.DateTime"? and 'System.DBNull'
Therefore, I suppose that only works if the second argument is a version of the first argument that does not allow null. So I went for:
datePrm.Value = nullableDate.HasValue ? nullableDate.Value : DBNull.Value;
but this does not work either:
The conditional expression type cannot be determined because there is no implicit conversion between "System.DateTime" and "System.DBNull"
But I do not want to convert between these types!
So far I can only work:
if (nullableDate.HasValue) datePrm.Value = nullableDate.Value; else datePrm.Value = DBNull.Value;
Is this really the only way to write this? Is there a way to get single-line traffic using a ternary operator?
Update: I really don't understand why ??? version does not work. MSDN says:
the operator returns the left operand if it is not NULL, or returns the correct operand.
This is exactly what I want!
Update2: Well, in the end, it was obvious:
datePrm.Value = nullableDate ?? (object)DBNull.Value;