Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable Object must have a value #2

I'm trying to reuse the same code I've always used but now it is encountering an error.

I'm looping through various user tables, and in there I do this:

DateTime dcdt = (DateTime)u.DateCreated;
DateTime lldt = (DateTime)u.LastLogon;
userRow["DateCreated"] = dcdt.ToShortDateString();

inside the loop. I get the error:

System.InvalidOperationException: Nullable object must have a value.

The error highlights "lldt" line, instead of "dcdt" which comes first. That is strange in and of itself. Both these fields in the database "allow nulls" is checked. And they both could be null or neither might be null.

The two values are both listed as DateTime? types through intellisense.

I don't understand why ASP.NET refuses to allow me to output blank for null dates. If it is empty/null, then logic would suggest that ASP.NET should just print nothing.

How else am I suppose to output null dates? I tried adding if statements to prevent trying to cast null DateTimes, but it doesn't help, it makes no sense.

like image 815
Dexter Avatar asked Jan 05 '12 20:01

Dexter


2 Answers

As you've said, the data type of u.LastLogon is DateTime?. This means that it may or may not have a value. By casting to DateTime, you are requiring it to have a value. In this case, it does not.

Depending on what you're trying to do with it, you may want to check the HasValue property:

userRow["LastLogon"] = u.LastLogin.HasValue ? 
                       (object) u.LastLogin.ToShortDateString() : DBNull.Value;

If your database LastLogon column is of DateTime type, then you should be able to do:

userRow["LastLogon"] = u.LastLogin.HasValue ? 
                       (object) u.LastLogin.Value : DBNull.Value;
like image 98
John Saunders Avatar answered Sep 25 '22 20:09

John Saunders


You need to do something like the following in your data access code:

DataTable  dt       = ExecuteSomeQuery() ;
object     value    = dt.Rows[0]["nullable_datetime_column"] ;
DateTime?  instance = value != null && value is DateTime ? (DateTime?)value : (DateTime?)null ) ;

If the column returned is NULL, it will be returned as a System.DBNull, otherwise it will be returned as an instance of DateTime (or whatever the appropriate mapped type is — int, string, etc). Consequently, you need to check the type of object returned from the query before trying to cast it.

like image 20
Nicholas Carey Avatar answered Sep 22 '22 20:09

Nicholas Carey