自定义 属性 为空

Custom property is null IdentityUser

我已经定制了 ApplicationUserDotaUserProfile 属性 已成功保存在另一个 table 的数据库中。但是当我试图得到这个 属性 时,例如

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var profile = user.DotaUserProfile;

我得到 null。 帮助您的代码片段:

public class ApplicationUser : IdentityUser
{
    public DotaUserProfile DotaUserProfile { get; set; }
    ...
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<DotaUserProfile> DotaUserProfile { get; set; }
    ...
}

注册码:

public async Task<ActionResult> DotaProfileRegister(DotaProfileRegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
        var dotaProfile = new DotaUserProfile()
        {
            Nickname = model.Nickname,
            University = model.University,
            RoleInGame = model.RoleInGame,
            HoursInGame = model.HoursInGame
        };
        user.DotaUserProfile = dotaProfile;
        await UserManager.UpdateAsync(user);
        return RedirectToAction("Index", "Home");
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

向 ApplicationUser 添加自定义属性后,您必须以不同的方式实例化 UserManager。

var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new MyDbContext()));

使用此管理器,您的 ApplicationUser 的属性应该被加载。

ApplicationUser user = await manager.FindByIdAsync(User.Identity.GetUserId());

MyDbContext 替换为您自己的 DbContext 实例。有关详细信息,请访问以下站点:http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx