[英]Custom property is null IdentityUser
我已經自定義了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);
}
將自定義屬性添加到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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.