2015-04-05 47 views
1

我已經定製ApplicationUserDotaUserProfile屬性已成功保存在另一個表中的數據庫中。但是,當我試圖讓這個屬性,例如,自定義屬性爲空IdentityUser

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

當您添加自定義屬性到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

+0

在您的建議更改後我的財產仍爲空 – WimmDeveloper 2015-04-05 19:21:31

+0

您可以嘗試使其如下所示:public virtual DotaUserProfile DotaUserProfile {get;組; }。看看這個鏈接有一個存儲在另一個表中的例子。 – 2015-04-05 19:31:10

+0

我的源代碼是這篇文章) – WimmDeveloper 2015-04-05 19:42:26