Custom属性为null IdentityUser

时间:2015-04-05 18:29:46

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

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

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

1 个答案:

答案 0 :(得分:0)

将自定义属性添加到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