问题描述
我有一个 DateTime?
,我正尝试使用 DbParameter
将其插入到字段中.我正在像这样创建参数:
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?"类型的操作数和'System.DBNull'
Operator '??' cannot be applied to operands of type 'System.DateTime?' and 'System.DBNull'
所以我想这只有在第二个参数是第一个参数的不可为空版本时才有效.然后我去了:
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'之间没有隐式转换
Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'System.DBNull'
但我不想在这些类型之间转换!
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:
??如果不为空,运算符返回左操作数,否则返回右操作数.
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;
这篇关于C# ADO.NET:空值和 DbNull —— 有没有更高效的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!