为什么我得到NullReferenceException

时间:2015-10-05 10:14:37

标签: c# asp.net-mvc asp.net-identity

我正在扩展ApplicationUser类,其中包含我需要在我的应用程序中使用的一些额外信息和关系。

这是我的ApplicationUser课程:

public class ApplicationUser : IdentityUser
{
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Display(Name = "Full Name")]
    public string FullName
    {
        get
        {
            return FirstName + " " + LastName;
        }
    }

    [Display(Name = "Job Title")]
    public string JobTitle { get; set; }

    public virtual ICollection<Permission> Permissions { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        userIdentity.AddClaim(new Claim("FullName", this.FullName));

        return userIdentity;
    }
}

我的Permission型号:

public class Permission : BaseEntity
{
    public int ID { get; set; }
    public string Name { get; set; }

    // Many to One
    public virtual ICollection<ApplicationUser> Users { get; set; }
}

Create()中的UsersController方法:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(CreateUserViewModel model)
{
    var selectedPermissions = model.Permissions.Where(x => x.IsChecked).Select(x => x.ID).ToList();

    if (ModelState.IsValid)
    {
        var user = new ApplicationUser {
            UserName = model.Email,
            Email = model.Email,
            PrivateEmail = model.PrivateEmail,
            FirstName = model.FirstName,
            LastName = model.LastName,
            JobTitle = model.JobTitle
        };


        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            // Remove all existing Roles
            var userRoles = await UserManager.GetRolesAsync(user.Id);
            var uRoles = String.Join(", ", userRoles.ToArray());
            await UserManager.RemoveFromRolesAsync(user.Id, uRoles);

            // Add selected Role
            await UserManager.AddToRoleAsync(user.Id, model.Role);

            foreach (var permissionID in selectedPermissions)
            {
                var permission = await db.Permissions.FindAsync(permissionID);
                if (permission != null)
                {
                    user.Permissions.Add(permission);
                }
            }
            await UserManager.UpdateAsync(user);

            return RedirectToAction("Index", "Default");
        }
        AddErrors(result);
    }

    // If we got this far, something failed, redisplay form
    var allPermissions = await db.Permissions.ToListAsync(); // returns List<Permission>
    var checkBoxListItems = new List<CheckBoxListItem>();
    foreach (var permission in allPermissions)
    {
        checkBoxListItems.Add(new CheckBoxListItem()
        {
            ID = permission.ID,
            Display = permission.Name,
            IsChecked = selectedPermissions.Contains(permission.ID)
        });
    }
    model.Permissions = checkBoxListItems;
    PopulateRolesDropDownList(model.Role);
    return View(model);

}

因此,在发布表单以创建新用户时,用户将保存到数据库,并且还会保存所选角色。但当它到达user.Permissions.Add(permission);行时,它会失败并显示错误:

System.NullReferenceException: Object reference not set to an instance of an object.

我添加了断点,可以看到当userpermission到达失败的行时,它们都不为空。

非常感谢有人能告诉我为什么会收到这个错误吗?

1 个答案:

答案 0 :(得分:1)

听起来像user.Permissions为空。

编辑:改述为答案,而不是问题。 : - )