简体   繁体   English

可空对象必须具有值datetime

[英]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# 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. 这里的问题是您将HasValue与null进行比较,因为它是一个布尔值,所以它始终为false。

You want to just have as below and same DisembarkDate . 您只需要具有以下内容和相同的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. item.cc_EmbarkDate.HasValue的值是布尔值,因此永远不能为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. 但是,如果有一个值,则返回值,否则返回null是没有意义的,因为那是nullable已包含的内容。 You would just do: 您只需执行以下操作:

EmbarkDate = item.cc_EmbarkDate,

DisembarkDate = item.cc_DisembarkDate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM