可空对象必须具有价值

时间:2015-04-10 18:05:36

标签: c# razor model-view-controller

我已经在这里检查了其他数百万条相同错误,但找不到任何有用的信息。

我有一个这样的模型:

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

如果BusinessLogic.GetUserByUserId(WebSecurity.CurrentUserId)失败以返回对象,例如WebSecurity.CurrentUserId返回零,那么.CommunityId将抛出异常(也就是说您尝试访问对象上的社区Id属性)那是NULL)。

将此分解为多行,如下所示,可以更容易地确定出错的地方:

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);

答案 2 :(得分:0)

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

相关问题