問題描述
我有一個 DateTime?
,我正嘗試使用 DbParameter
將其插入到字段中.我正在像這樣創(chuàng)建參數(shù):
I've got a DateTime?
that I'm trying to insert into a field using a DbParameter
. I'm creating the parameter like so:
DbParameter datePrm = updateStmt.CreateParameter();
datePrm.ParameterName = "@change_date";
然后我想將 DateTime?
的值放入 dataPrm.Value
中,同時考慮 null
s.
And then I want to put the value of the DateTime?
into the dataPrm.Value
while accounting for null
s.
我最初以為我會很聰明:
I thought initially I'd be clever:
datePrm.Value = nullableDate ?? DBNull.Value;
但由于錯誤而失敗
運算符??"不能應用于System.DateTime?"類型的操作數(shù)和'System.DBNull'
Operator '??' cannot be applied to operands of type 'System.DateTime?' and 'System.DBNull'
所以我想這只有在第二個參數(shù)是第一個參數(shù)的不可為空版本時才有效.然后我去了:
So I guess that only works if the second argument is a non-nullable version of the first argument. So then I went for:
datePrm.Value = nullableDate.HasValue ? nullableDate.Value : DBNull.Value;
但這也不起作用:
無法確定條件表達式的類型,因為'System.DateTime'和'System.DBNull'之間沒有隱式轉(zhuǎn)換
Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'System.DBNull'
但我不想在這些類型之間轉(zhuǎn)換!
But I don't want to convert between those types!
到目前為止,我唯一能開始工作的是:
So far the only thing I can get to work is:
if (nullableDate.HasValue)
datePrm.Value = nullableDate.Value;
else
datePrm.Value = DBNull.Value;
這真的是我寫這篇文章的唯一方式嗎?有沒有辦法讓單行使用三元運算符工作?
Is that really the only way I can write this? Is there a way to get a one-liner using the ternary operator to work?
更新:我真的不明白為什么 ??版本不起作用.MSDN 說:
Update: I don't really get why the ?? version doesn't work. MSDN says:
??如果不為空,運算符返回左操作數(shù),否則返回右操作數(shù).
The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.
這正是我想要的!
更新 2: 嗯,最后很明顯:
datePrm.Value = nullableDate ?? (object)DBNull.Value;
推薦答案
啊哈!我找到了比@Trebz 更有效的解決方案!
Ah ha! I found an even more efficient solution than @Trebz's!
datePrm.Value = nullableDate ?? (object)DBNull.Value;
這篇關(guān)于C# ADO.NET:空值和 DbNull —— 有沒有更高效的語法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!