[英]best method to solve Nullable object must have a value in datetime
[英]Nullable object must have a value datetime
数据库
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
}
错误:可为空的对象必须具有值什么问题,谢谢
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
这里的问题是您将HasValue
与null进行比较,因为它是一个布尔值,所以它始终为false。
您只需要具有以下内容和相同的DisembarkDate
。
EmbarkDate = item.cc_EmbarkDate.HasValue ? (DateTime?)item.cc_EmbarkDate.Value : item.cc_EmbarkDate = null
您使用的是条件表达式,但条件错误,整个表达式毫无意义。 同样,第三个操作数具有将空值赋给您已经知道为空值的副作用(代码气味)。
item.cc_EmbarkDate.HasValue
的值是布尔值,因此永远不能为null。 这使表达式为真,即使没有值,您也将始终尝试从可为空的值中获取值。
您将要做的是:
EmbarkDate = item.cc_EmbarkDate.HasValue ? item.cc_EmbarkDate.Value : null,
DisembarkDate = item.cc_DisembarkDate.HasValue ? item.cc_DisembarkDate.Value : null
但是,如果有一个值,则返回值,否则返回null是没有意义的,因为那是nullable已包含的内容。 您只需执行以下操作:
EmbarkDate = item.cc_EmbarkDate,
DisembarkDate = item.cc_DisembarkDate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.