Erik
Erik

Reputation: 21

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)));

Upvotes: 1

Views: 4974

Answers (3)

Nicolas Repiquet
Nicolas Repiquet

Reputation: 9265

Use SqlDateTime instead :

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

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

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

Upvotes: 3

Oded
Oded

Reputation: 499352

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.

Upvotes: 0

Related Questions