Baba
Baba

Reputation: 2219

Store DBnull in database for date column that accepts null

I have a DateTime value that I will like to save to the database. The column allows null in the database. When I try to run the code below I get this error message.

Type of conditional expression cannot be determined because there is no implicit conversion between system.dbnull and system.datetime

How can I store null or empty value for a date column?

public class ExcelData
{
  public DateTime? DateValue1 { get; set; }
}

DateValue1 = col28Value == null ? DBNull.Value : Convert.ToDateTime(col28Value)

Upvotes: 2

Views: 1618

Answers (4)

SLaks
SLaks

Reputation: 887413

The conditional operator requires that one of its types be convertible to the other.
It will not try to find the closest common base type.

Since DBNull and DateTime have nothing in common, it fails.

You need to cast either side to object.


However, that won't work either.
DBNull.Value is a special object used for certain APIs in System.Data.
It has nothing to do with nullable types.

Instead, you need use null itself.
Since null is not convertible to DateTime, you will also need to cast it to DateTime?. Alternatively, you can write new DateTime?(), which will create an empty (null) Nullable<DateTime> value.

Upvotes: 3

Jonesopolis
Jonesopolis

Reputation: 25370

when you do this:

DateValue1 = col28Value == null ? DBNull.Value : Convert.ToDateTime(col28Value)

you may be doing :

DateValue1 = DbNull.Value;

which is not possible. So replace DbNull.Value with null

Upvotes: 0

banging
banging

Reputation: 2550

Work with SqlParameter and not their value like so..

SqlParameter sp = col28Value == null ? new SqlParameter("@whatever", DBNull.Value) : new SqlParameter("@whatever", col28Value);

Upvotes: 0

Icarus
Icarus

Reputation: 63956

It's telling you that you can't declare a Nullable<DateTime> and assign it a DBNull.Value which is not the same as null

Your code should simply be:

DateValue1 = col28Value ==null? (DateTime?)null: Convert.ToDateTime(col28Value)

Upvotes: 5

Related Questions