可空对象必须有一个值#2 [英] Nullable Object must have a value #2

查看:290
本文介绍了可空对象必须有一个值#2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重复使用相同的code我一直使用,但现在它遇到一个错误。

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.

错误亮点LLDT行,而不是它是第一位的DCDT。这本身是奇怪。这两个数据库中的允许空值,这些领域被选中。他们都可能为空或者都可能为空。

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.

我不明白为什么ASP.NET拒绝让我输出空白空日期。如果为空/空,那么逻辑会建议ASP.NET应该只是打印罢了。

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.

要不然怎么是我该输出空日期?我尝试添加if语句prevent尝试投放空DateTime是否,但它并没有帮助,这是没有意义的。

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.

推荐答案

正如你所说的, u.LastLogon的数据类型日期时间?。这意味着,它可以或可以不具有一个值。通过转换成的DateTime ,你需要它有一个值。在这种情况下,不

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.

根据你想用它做什么,你可能要检查的的HasValue 属性:

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;


如果你的数据库 LastLogon 列是DateTime类型的,那么你应该能够做到:


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;

这篇关于可空对象必须有一个值#2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆