我已定制ApplicationUser
。 DotaUserProfile
属性已成功保存在另一个表的数据库中。但是当我试图获得这个属性时,例如,
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);
}
答案 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