2016-12-25 69 views
3

我使用MVC 5和6 EF(Datafirst),使用msssql管理工作室。到身份添加屬性在MVC 5,使用實體框架

我創建了一個新的MVC項目,提出了建立數據庫(AspNetUsers等)

我還創建了一個名爲的UserDetails新表,其目的是包含用戶的詳細信息通過它的ID(所以我創建的UserDetails用戶ID列AspNetUsers id列之間的鏈接)

所以我下面的代碼添加

public class ApplicationUser : IdentityUser 
{ 

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
    { 

     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
     // Add custom user claims here 
     userIdentity.AddClaim(new Claim("FirstName", FirstName.ToString())); 

     return userIdentity; 
    } 
    //Extended Propeties 
    public string FirstName { get; set; } 

} 

但是,當然它不工作的,我看着在互聯網上超過4小時了,可有人請引導我 ?我是MVC的新手,一切看起來都很複雜。 我也有以下的靜態方法:

public static class IdentityExtensions 
{ 
    public static string GetFirstName(this IIdentity identity) 
    { 
     var claim = ((ClaimsIdentity)identity).FindFirst("FirstName"); 
     // Test for null to avoid issues during local testing 
     return (claim != null) ? claim.Value : string.Empty; 
    } 
} 

爲了得到它的視圖,並顯示它.. 我的目標是基於對1連接視圖從另一個表顯示數據(的UserDetails) -1從AspNetUsers(UserDetails.UserId == AspNetUsers.Id)

+0

如果您在ApplicationUser類添加屬性應該正常工作......請告訴我問題?你是否在添加該屬性後更新了數據庫? .... –

+0

@DaniyalAwan「的模式支持了‘ApplicationDbContext’環境已經改變,因爲創建數據庫。考慮使用的Code First遷移來更新數據庫」,因爲它試圖獲取名字,當我嘗試登錄,它的但它不「噸AspNetUsers存在,它在的UserDetails .. –

+1

沒有,你已經在applicationUser創建名字,不是的UserDetails所以怎麼能說是在的UserDetails。我認爲這個問題是您創建的名字但沒有更新的數據庫.. 。使用遷移來更新數據庫 –

回答

0

所有你需要做的是擴展IdentityUser類,然後添加像FirstName等自定義屬性。然後,因爲你首先使用EntityFramework數據庫,你需要在包管理器控制檯enable-migrations中使用此命令啓用遷移,然後在更新之後添加初始遷移,如add-migration initialMigration數據庫使用遷移命令update-database,數據庫中的AspNetUsers表現在將添加新的列。使用遷移,以保持你的數據庫同步與您的模型

0

如果有兩個表可以使用Eagerly Loading從另一個得到一個實體的細節之間的連接是否正確。