简体   繁体   中英

DateTime and DbNull.Value

Does anyone have an idea why this works:

if (_item.Created == DateTime.MinValue)
{
  ListSqlParam.Add(new SqlParameter("@TransactionCreated", DBNull.Value));
}
else
{
  ListSqlParam.Add(new SqlParameter("@TransactionCreated", _item.Created));
}

but not this:

ListSqlParam.Add(new SqlParameter("@TransactionCreated",((_item.Created == DateTime.MinValue) ? DBNull.Value : _item.Created)));

The reason is that the conditional operator is an expression of a specific type. This specific type is infered by the compiler based on the types of the expressions in the two branches of the operator.
In your code, this specific type can't be infered by the compiler because DBNull.Value and _item.Created are of different and unrelated types. You can't cast either one to the type of the other one.

To make it work, cast at least one branch to object :

(_item.Created == DateTime.MinValue) ? (object)DBNull.Value : _item.Created

When using the conditional operator , both types returned by the different sides of the conditional (the true and the false branches) should be the same or be implicitly convertible to each other.

DBNull.Value and DateTime are not such values.

改为使用SqlDateTime

_item.Created == DateTime.MinValue ? SqlDateTime.Null : new SqlDateTime(_item.Created)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM