简体   繁体   中英

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

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

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

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