天天看點

關于DBNull.Value

I've got a <code>DateTime?</code> that I'm trying to insert into a field using a <code>DbParameter</code>. I'm creating the parameter like so:

And then I want to put the value of the <code>DateTime?</code> into the <code>dataPrm.Value</code> while accounting for <code>null</code>s.

I thought initially I'd be clever:

but that fails with the error

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:

but that doesn't work either:

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:

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?

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.

That's exactly what I want!

Update2: Well it was kind of obvious in the end:

本文轉自 h2appy  51CTO部落格,原文連結:http://blog.51cto.com/h2appy/415825,如需轉載請自行聯系原作者

繼續閱讀