【问题标题】:nullable object must have value可空对象必须有值
【发布时间】:2015-04-10 18:05:35
【问题描述】:

我在这里检查了数百万个其他帖子是否存在相同的错误,但找不到任何有用的信息。

我有一个这样的模型:

public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int? CommunityId { get; set; }
    public string Email { get; set; }
    public Int64? Phone { get; set; }
    public AlertMode AlertMode { get; set; }
    public string B64EncodedImage { get; set; }
}

当我从数据库中获取用户时,分配如下所示:

User user = new User()
{
    UserId = Convert.ToInt32(reader["UserId"]),
    UserName = Convert.ToString(reader["UserName"]),
    CommunityId = reader["CommunityId"] == DBNull.Value
        ? (int?)null : Convert.ToInt32(reader["CommunityId"]),
    Phone = reader["Phone"] == DBNull.Value
        ? (Int64?)null : Convert.ToInt64(reader["Phone"]),
    AlertMode = (AlertMode)Int32.Parse(reader["AlertMode"].ToString()),
    Email = Convert.ToString(reader["Email"]),
    B64EncodedImage = Convert.ToString(reader["B64EncodedImage"])
};

当我调用这段代码时:

        @((BusinessLogic.GetUserByUserId(WebSecurity.CurrentUserId)).CommunityId.HasValue
                ? "COMMUNITYID"
                : "Not set!"
             )

我收到此错误:

Nullable object must have a value.

在这一行:

@((BusinessLogic.GetUserByUserId(WebSecurity.CurrentUserId)).CommunityId.HasValue

有什么想法吗?

================================================ ======================== 编辑:

我更改了代码以将用户作为模型返回到视图:

    public ActionResult Manage()
    {
        User user = BusinessLogic.GetUserByUserId(WebSecurity.CurrentUserId);
        return View(user);
    }

逐步执行,模型已填充,但 CommunityId 为空(应该没问题)

            @(Model.CommunityId.HasValue
                ? "COMMUNITYID"
                : "Not set!"
             )

现在我明白了:

Cannot perform runtime binding on a null reference

【问题讨论】:

    标签: c# razor model-view-controller


    【解决方案1】:

    您的BusinessLogic.GetUserByUserId 函数是否可能返回空值,也许它无法识别用户 ID?如果您使用的是 VS 调试器,您应该能够检查变量的状态,或者可能将它们分成单独的行以使调试更容易。

    【讨论】:

      【解决方案2】:

      如果 BusinessLogic.GetUserByUserId(WebSecurity.CurrentUserId) 未能返回对象,例如 WebSecurity.CurrentUserId 返回零,则 .CommunityId 将引发异常(也就是您尝试访问对象上的 Community Id 属性)空)。

      像下面这样将它分成多行可以更容易地确定哪里出了问题:

      var user = BusinessLogic.GetUserByUserId(WebSecurity.CurrentUserId);
      if (user != null)
      {
          return user.CommunityId.HasValue? "COMMUNITYID" : "Not set!";
      }
      
      // throw an ArgumentNullException (or something similiar) so that you know what happened
      throw new ArgumentNullExpception("user);
      

      【讨论】:

        【解决方案3】:

        问题在于,在视图中的另一段代码中,我试图访问空值,而调试器错误地指向错误的错误位置。

        【讨论】:

        • 这可以解释为什么我无法重新创建异常:)。你应该排除这个答案。
        猜你喜欢
        • 2012-05-20
        • 1970-01-01
        • 2010-12-26
        • 1970-01-01
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多