Nullable object must have a value datetime

database

EmbarkDate       [] allowNulls checked
DisembarkDate    [] allowNulls checked

  update [dbo].[t_CrewContract] set EmbarkDate= null where cc_ID='AEDAEC31-6108-CE8F-97DF-114FD87A6257'
  update [dbo].[t_CrewContract] set DisembarkDate= null where cc_ID='AEDAEC31-6108-CE8F-97DF-114FD87A6257' 

c#

     public DateTime? EmbarkDate { get; set; }
     public DateTime? DisembarkDate{ get; set; }

ContractItems.Add(new ContractItem
                    {
   EmbarkDate = item.cc_EmbarkDate.HasValue != null ? item.cc_EmbarkDate.Value : item.cc_EmbarkDate = null,

   DisembarkDate = item.cc_DisembarkDate.HasValue != null ? item.cc_DisembarkDate.Value     : item.cc_DisembarkDate = null,

});

if(activeContract.EmbarkDate == null)
{
  //...codes
}

error : Nullable object must have a value What's the problem thank you

Upvotes: 1

Views: 12574

Answers (2)

Darren Kopp
Darren Kopp

Reputation: 77697

EmbarkDate = item.cc_EmbarkDate.HasValue != null 
    ? item.cc_EmbarkDate.Value : item.cc_EmbarkDate = null,

DisembarkDate = item.cc_DisembarkDate.HasValue != null
    ? item.cc_DisembarkDate.Value : item.cc_DisembarkDate = null

The problem here is you are comparing HasValue to null, which will always be false since it's a boolean.

You want to just have as below and same DisembarkDate.

EmbarkDate = item.cc_EmbarkDate.HasValue ? (DateTime?)item.cc_EmbarkDate.Value : item.cc_EmbarkDate = null

Upvotes: 4

Guffa
Guffa

Reputation: 700880

You are using a conditional expression, but the condition is wrong, and the whole expression is pointless. Also, the third operand is having the side effect (code smell) of assigning null to a value that you already know is null.

The value of item.cc_EmbarkDate.HasValue is a boolean, so it can never be null. That makes the expression true, and you will always try to get the value from the nullable, even when there is no value.

What you would be doing is:

EmbarkDate = item.cc_EmbarkDate.HasValue ? item.cc_EmbarkDate.Value : null,

DisembarkDate = item.cc_DisembarkDate.HasValue ? item.cc_DisembarkDate.Value : null

However, getting the value if there is one and null otherwise is pointless, as that is what the nullable already contains. You would just do:

EmbarkDate = item.cc_EmbarkDate,

DisembarkDate = item.cc_DisembarkDate

Upvotes: 2

Related Questions